0

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

?>
Community
  • 1
  • 1

1 Answers1

0

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);
Simon
  • 816
  • 2
  • 7
  • 16
  • Your solution is incomplete (and does not work on my computer), but on the page you link to I found another tip : replace $post_data with http_build_query($post_data). Combining this with the header works on my computer. Thanks for your indirect help – Warren Beadus Feb 16 '15 at 10:08
  • @WarrenBeadus - Glad it's sorted and could be of some help :) – Simon Feb 18 '15 at 06:43