PHP使用stream_context_create模拟HTTP请求
本实例详细解析了如何在 PHP 中借助 stream_context_create() 函数来模拟 POST 与 GET 请求,供开发者参考借鉴。
在实际开发中,常需在服务端模拟 HTTP 请求,即将数组数据发送至指定地址。虽然 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 '';
print_r( $data );
echo '';
执行上述代码后的输出结果如下:
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 这类直接操作文件名而无文件句柄的函数尤为实用。该函数不仅能增加 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 程序设计工作提供有益帮助。