PHP实用函数:stream_context_create

本文介绍如何使用PHP的stream_context_create函数模拟POST请求,包括设置请求方法、头信息、内容及超时处理,适用于不使用curl库的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候,我们需要在服务器端模拟post/get请求,也就是在php程序中去实现模拟,该怎么做呢?或者说,在php程序里,给你一个数组,如何将这个数组post/get到另一个地址呢?当然,实用curl很容易办到,那么,不使用curl库又该怎么办呢?其实,在php程序里已经有相关的函数了,它就是stream_context_create。

伪代码:

$data = array(
‘foo’=>‘bar’,
‘baz’=>‘boom’,
‘site’=>‘www.lai18.com’,
‘name’=>‘lai18’
);
d a t a = h t t p b u i l d q u e r y ( data = http_build_query( data=httpbuildquery(data);

    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencode',
            'content' => $data,
            'timeout' => 60,
        )
    );
    $url = "http://www.lai18.net/";
    $context = stream_context_create($options);
    $result = file_get_contents($url,false,$context);
    
    var_dump($result);

http://www.lai18.com 的代码为:
$data = $_POST;
echo ‘

’;
print_r( $data );
echo ‘
’;

运行结果为:
Array
(
[foo] => bar
[baz] => boom
[site] => www.lai18.com
[name] => lai18
)

一些要点讲解:
1:stream_context_create作用:创建并返回一个文本数据流并应用各种选项,可用于fopen()、file_get_contents、soap等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。
2:stream_context_create还能通过增加timeout选项来解决file_get_contents的超时处理。
$opts = array(
‘http’=>array(
‘method’=>“GET”,
‘timeout’=>60,
)
);
//创建数据流上下文
c o n t e x t = s t r e a m c o n t e x t c r e a t e ( context = stream_context_create( context=streamcontextcreate(opts);
$html =file_get_contents(‘http://www.lai18.com’, false, $context);

3:工作中解决soap连接超时:
$stream = stream_context_create([“http” => [“timeout” => 3]]);//超时时间

    try{
        if(!$address){
            return false;
        }
        $address = $this->dealAddress($address);

        $soapClientOptions = [
            'trace' => true,
            'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP,
            'cache_wsdl' => 0,
            'stream_context' => $stream, //定义连接超时为3秒
        ];

        $client = new \SoapClient($this->brightDairyApiUrl, $soapClientOptions);
        $arg0 = ['arg0' => $address];
        $responseObject = $client->queryAddress($arg0);
        $response = json_decode($responseObject->return,true);
        if(!isset($response['success']) || !$response['success'] || !isset($response['blockId']) || !$response['blockId']){
            return false;
        }
        return true;
    }catch (\SoapFault $e){
        //连接光明超时、连接不上,为了不影响用户下单,直接返回true
        return true;
    }

原文:https://blog.youkuaiyun.com/hello_katty/article/details/46371845

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值