【问题标题】:fopen not working : why is $_POST empty?fopen 不工作:为什么 $_POST 是空的?
【发布时间】:2015-04-16 15:23:54
【问题描述】:

我有两个文件active.php 和passive.php。 正如解释的那样,我希望 active.php 在没有用户交互的情况下将数据发布到passive.php here。 如果我的代码有效,最后 $_POST 数组应该包含 'Name'=>'John Doe' 就像我的导航器告诉我的那样是空的。我做错了什么?

我完全知道有使用 Javascript(如 here 解释)或 cURL(如 here 解释)的解决方案,但这个问题专门针对 PHP-only 方法,所以请不要 发表任何涉及 Javascript 或 cURL 的评论或答案。

passive.php 的内容:

<?php
     var_dump($_POST);
  ?>

active.php 的内容:

  <?php

   $post_data=array('Name'=>'John Doe');
   $url='http://localhost:8888/passive.php';
   $params = array('http' => array(
                'method' => 'POST',
                'content' => $post_data
             ));
   $ctx = stream_context_create($params);
   $fp = @fopen($url, 'rb', false, $ctx);
   $response = @stream_get_contents($fp);
   fclose($fp);
   var_dump($response);

?>

【问题讨论】:

  • 可能想尝试在您的流上下文中添加一个标头

标签: php post


【解决方案1】:

在 PHP 手册页本身found here 上,评分最高的评论解释了如何使用流执行 POST 操作。正如上面的评论中提到的,你只是缺少一个标题

$post_data=array('Name'=>'John Doe');
$url='http://localhost:8888/passive.php';

$params = array(
  'http' => array
  (
      'method' => 'POST',
      'header'=>"Content-Type: application/x-www-form-urlencoded",
      'content' => $post_data
  )
);

$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);

$response = stream_get_contents($fp);

【讨论】:

  • 您的解决方案不完整(并且不适用于我的计算机),但在您链接到的页面上,我发现了另一个提示:将 $post_data 替换为 http_build_query($post_data)。将此与标题结合在我的计算机上工作。感谢您的间接帮助
  • @WarrenBeadus - 很高兴它已排序并且可能会有所帮助:)
猜你喜欢
  • 2019-12-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多