PHP如何使用stream_context_create()模拟POST/GET请求

发布时间:2021-08-31 09:23:29 作者:小新
来源:亿速云 阅读:133

这篇文章主要介绍了PHP如何使用stream_context_create()模拟POST/GET请求,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

具体如下:

有时候,我们需要在服务器端模拟 POST/GET 等请求,也就是在 PHP 程序中去实现模拟,改怎么做到呢?或者说,在 PHP 程序里,给你一个数组,如何将这个数组 POST/GET 到另外一个地址呢?当然,使用 CURL 很容易办到,那么如果不使用 CURL 库,又该怎么办呢?其实,在 PHP 里已经有相关的函数实现了,这个函数就是接下来要讲的 stream_context_create()。

直接 show you the code,这是最好的方法:

$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
)

一些要点讲解:

1. 以上程序用到了 http_build_query() 函数,如果需要了解,可以参看 前面一篇《PHP使用http_build_query()构造URL字符串的方法》。

2. stream_context_create() 是用来创建打开文件的上下文件选项的,比如用POST访问,使用代理,发送header等。就是 创建一个流,再举一个例子吧:

$context = stream_context_create(array( 
    'http' => array( 
        'method' => 'POST', 
        'header' => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)). 
        "Content-type: application/x-www-form-urlencoded\r\n", 
        'content' => http_build_query(array('status' => $message)), 
        'timeout' => 5, 
    ), 
)); 
$ret = file_get_contents('http://twitter.com/statuses/update.xml', false, $context);

3. stream_context_create创建的上下文选项即可用于流(stream),也可用于文件系统(file system)。对于像 file_get_contents、file_put_contents、readfile直接使用文件名操作而没有文件句柄的函数来说更有用。stream_context_create增加header头只是一部份功能,还可以定义代理、超时等。这使得访问web的功能不弱于curl。

4. stream_context_create() 作用:创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。

5. stream_context_create 还能通过增加 timeout 选项解决file_get_contents超时处理:

$opts = array(
  'http'=>array(
  'method'=>"GET",
  'timeout'=>60,
 )
);
//创建数据流上下文
$context = stream_context_create($opts);
$html =file_get_contents('http://localhost', false, $context);
//fopen输出文件指针处的所有剩余数据:
//fpassthru($fp); //fclose()前使用

感谢你能够认真阅读完这篇文章,希望小编分享的“PHP如何使用stream_context_create()模拟POST/GET请求”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

推荐阅读:
  1. 云服务器centOS怎么部署php
  2. PHP中 mysqli_embedded_server_start函数如何使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:Linux下如何编译redis和phpredis

下一篇:php如何读取torrent种子文件内容

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》