doufu5521 2015-02-16 06:52
浏览 25
已采纳

fopen不工作:为什么$ _POST为空?

I have two files active.php and passive.php. I want active.php to post data without user interaction to passive.php, as explained here. If my code worked, in the end the $_POST array should contain 'Name'=>'John Doe' instead of being empty as my navigator informs me. What did I do wrong ?

I am fully aware that there are solutions using either Javascript (as explained here ) or cURL (as explained here ), but this question is specifically about the PHP-only method, so please do not post any comment or answer involving Javascript or cURL.

Contents of passive.php :

<?php
     var_dump($_POST);
  ?>

Contents of 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);

?>
  • 写回答

1条回答 默认 最新

  • dongsun2789 2015-02-16 07:51
    关注

    On the PHP manual page itself found here the top rated comment explains how to perform a POST operation using stream. As mentioned in the comment above, you're just missing a header

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?