scriptkiddie1
scriptkiddie1

Reputation: 497

Not working : Using file_get_contents to post data

I am learning and I am trying post data to 4.php and get the result to printed on range.php.. I have already seen the How to post data in PHP using file_get_contents?

<?php
error_reporting(-1);

$postdata = http_build_query(
array('var1' => 'sugumar',
    'var2' => 'doh')
);

$opts = array('http'=>array(
  'method'=>'post',
  'header'=> 'Content-Type: application/x-www-form-urlencoded',
  'content'=> $postdata

 )
);

$context = stream_context_create($opts);

 $result = file_get_contents('http://localhost/php/4.php', false, $context);
 print_r($result);//DOESN'T PRINT ANYTHING
?>

4.php

 print_r($_REQUST);
$postdata = http_build_query($_POST);
print_r($postdata);

I want to know why it's not printing anything... please help me..

Upvotes: 1

Views: 6862

Answers (1)

codisfy
codisfy

Reputation: 2183

I have updated your code using code from the PHP manual and changes like adding PHP tags to 4.php and fixing typo in $_REQUEST.

Here is the updated code, which seems to be working for me:

<?php

$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);

$context_options = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );

$context = stream_context_create($context_options);
 $result = file_get_contents('http://localhost/php/4.php', false, $context);
 var_dump($result);//prints something :)
?>

4.php

<?php

 print_r($_REQUEST);
$postdata = http_build_query($_POST);
print_r($postdata);

Upvotes: 3

Related Questions