最新消息: 新版网站上线了!!!

php模拟浏览器实现http请求,模拟post发送请求,调用接口

一、代码

1、index.php

在index.php中,请求http://127.0.0.1/test1/test2.php文件,发送http请求。

$data1 = array('foo','bar','baz','boom','cow'=>'milk','php'=>'hypertext processor');
$data = http_build_query($data1);
$options = array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type:application/x-www-form-urlencoded',
        'content' => $data
        //'timeout' => 60 * 60 // 超时时间(单位:s)
    )
);
$url = "http://127.0.0.1/test1/test2.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;


2、test2.php

test2.php文件中输出index.php传递的参数,但是直接访问test2.php文件,不会输出任何结果,接收不到任何结果,只有被远程调用,传递参数才能正常输出。

$data = $_POST;
echo '<pre>';
print_r( $data );
echo '</pre>';


3、执行index.php文件结果

$result = file_get_contents($url, false, $context) 输出test2.php打印的数据。

Array
(
    [0] => foo
    [1] => bar
    [2] => baz
    [3] => boom
    [cow] => milk
    [php] => hypertext processor
)


转载请注明:谷谷点程序 » php模拟浏览器实现http请求,模拟post发送请求,调用接口