PHP实用函数:stream_context_create()模拟POST/GET

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'=>'www.lai18.com', 
	'name'=>'lai18'); 
	
$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://www.lai18.net/";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo $result;

http://www.lai18.com 的代码为:

$data = $_POST;

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


运行结果为:

Array
(
    [foo] => bar
    [baz] => boom
    [site] => www.lai18.com
    [name] => lai18
)


一些要点讲解(参考: http://www.lai18.com/content/425476.html):
<
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
当使用curl库或file_get_contents函数进行POST请求时,您可以按照以下示例传递数据: 1. 使用curl库: ```php $url = "http://192.168.100.201:5678/decrypt/"; $data = ["path" => "H:/project/河南森博建筑工程有限公司开标一览表.xls", "my_directory" => "f68dd48b10364f8b9813996ffebb7361", "new_name" => "河南森博建筑工程有限公司", "pwd" => "123456"]; $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); $response = curl_exec($curl); curl_close($curl); // 处理响应数据 ``` 2. 使用file_get_contents函数进行POST请求的方式有所不同,需要使用`http_build_query`函数将数据转换为查询字符串,并使用`stream_context_create`函数设置上下文选项: ```php $url = "http://192.168.100.201:5678/decrypt/"; $data = ["path" => "H:/project/河南森博建筑工程有限公司开标一览表.xls", "my_directory" => "f68dd48b10364f8b9813996ffebb7361", "new_name" => "河南森博建筑工程有限公司", "pwd" => "123456"]; $options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($data) ) ); $context = stream_context_create($options); $response = file_get_contents($url, false, $context); // 处理响应数据 ``` 请注意,这是一个示例,您需要根据实际情况修改`$url`和`$data`的值以适应您的API和数据需求。另外,确保您的服务器可以访问指定的IP地址和端口,并且API端点正确响应您的请求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值