使用stream_context_create()模拟POST/GET请求的方法

Posted 枫叶那个飘啊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用stream_context_create()模拟POST/GET请求的方法相关的知识,希望对你有一定的参考价值。

  有时候,我们需要在服务器端模拟 POST/GET 等请求,也就是在 php 程序中去实现模拟。

  或者说,在 PHP 程序里,给你一个数组,如何将这个数组 POST/GET 到另外一个地址呢?当然,使用 CURL 很容易办到,那么如果不使用 CURL 库,又该怎么办呢?其实,在 PHP 里已经有相关的函数实现了,这个函数就是接下来要讲的 stream_context_create()。代码如下:

$data = array(
    foo=>bar, 
    baz=>boom, 
    site=>localhost, 
    name=>nowa magic); 
$data = http_build_query($data); 
//$postdata = http_build_query($data);
$options = array(
    http => array(
        method => POST,
        header => Content-type:application/x-www-form-urlencoded,
        content => $data
        //‘timeout‘ => 60 * 60 // 超时时间(单位:s)
    )
);
$url = "http://localhost/test2.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;

http://localhost/test2.php 的代码为:

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

运行结果为:

Array
(
  [foo] => bar
  [baz] => boom
  [site] => localhost
  [name] => nowa magic
)

以上是关于使用stream_context_create()模拟POST/GET请求的方法的主要内容,如果未能解决你的问题,请参考以下文章

PHP stream_context_create()作用和用法分析

file_get_contents(): SSL operation failed with code 1...解决办法和stream_context_create作用

file_get_contents(): SSL operation failed with code 1...解决办法和stream_context_create作用

php http_build_query stream_context_create post请求

在PHP中通过TCP发送XML EPP请求

php脚本超时 结束执行代码