1

I am using the example function given in this post:

<?php
function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}
?>

I also tried a similar approach using file_get_contents(), like this:

$options = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>
      "Accept-language: en\r\n".
      "Content-type: application/x-www-form-urlencoded\r\n",
    'content'=>http_build_query(
        array(
            'arg1'=>'arg_data_1',
            'oper'=>'get_data',
            'arg2'=>'arg_data_2',
            'id_number'=>'7862'
        ),'','&'
    )
));

$context = stream_context_create($options);
$refno = file_get_contents('/path/to/script/script.php',false,$context);

var_dump($refno);

With both these scripts, the response from the server script is the same, and it is the TEXT of the script.php. The code of the server script is never begin executed, and the text content (the PHP code) of the script is being returned to the original script.

A little strange that it doesn't return all the text, but just certain pieces... I tried making a test script (test.php) that just contains:

<?php
echo '{"a":1,"b":2,"c":3,"d":4,"e":5}';
?>

but that doesn't return anything from the POST request, so I didn't include that. The script.php is a must longer script that does a lot of logic and MySQL queries then returns a JSON object.

The desired output will be to have the PHP code execute and return a JSON object (the way it works with ajax).

What am I doing wrong?

jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160
  • 1
    You're simply reading the file locally - you're bypassing the webserver completely, so the PHP code isn't being processed into finished content. – andrewsi Sep 19 '12 at 17:51
  • http://stackoverflow.com/questions/2367458/php-post-data-with-fsockopen – Motomotes Sep 19 '12 at 17:54
  • I had run into a problem with curl and accessing the scripts on my local machine. It looks like it was the same problem as the answer suggests. – jeffery_the_wind Sep 19 '12 at 18:01

1 Answers1

3

You are trying access script localy. You must call it like any other external script like

$refno = file_get_contents('http://yourhost/path/to/script/script.php',false,$context);
MrSil
  • 608
  • 6
  • 12