不工作:使用file_get_contents发布数据

时间:2017-03-05 06:29:53

标签: php

我正在学习,我正在尝试将数据发布到4.php并将结果打印到range.php上..我已经看过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);

我想知道它为什么不打印任何东西......请帮帮我..

1 个答案:

答案 0 :(得分:1)

我已经使用PHP手册中的代码更新了您的代码,并且更改了将PHP标记添加到4.php并修复了$_REQUEST中的拼写错误。

这是更新后的代码,似乎对我有用:

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