当前位置:首页 > PHP > 正文内容

php如何将curl请求内容流式返回

高老师4个月前 (05-19)PHP129

应用场景:客户调用服务端,服务器端stream方式调用ai接口,服务器端stream方式返回给客户端,全程sse支持。

代码参考:

/**
 * 通过Curl+Stream方式提交数据
 *
 * @param string $url
 * @param null $header
 * @param null $data
 * @param Closure $closure
 * @throws
 */
function curlWithStream(string $url, $header = null, $data = null, $closure)
{
    if (!($closure instanceof Closure)) {
        throw new \think\Exception('closure must instanceof Closure');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
    curl_setopt($ch, CURLOPT_TCP_KEEPALIVE, 1);
    curl_setopt($ch, CURLOPT_TCP_KEEPIDLE, 120);
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $str) use ($closure) {
        return $closure($ch, $str);
    });
    curl_exec($ch);
    curl_close($ch);
}

调用例子:

curlWithStream('参数1','参数2','参数3',function($ch, $str){
	return strlen($str);
});

扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.20230611.cn/post/765.html

分享给朋友:

“php如何将curl请求内容流式返回” 的相关文章

PHP session和cookie的关联

PHP session和cookie的关联

先看看下面的代码:<?php session_start(); $_SESSION['username']='lucy'; ?>当我们请求访问上面的脚本,默认会在我们的客户端生成一个名为PHPSESSID的cookie,我这里的值是PHPSESSID=...

PHP中Session文件过多的解决方法

PHP中Session文件过多的解决方法

PHP的session文件夹默认保存在同一个文件,随着访客的增多,访问的速度会非常慢,例如部分管理系统后台每天登陆1000次,1个月就创建了30000个session文件,一年后是多少?假设这个系统的用户是上万人呢?方法1:每个网站使用自己的session文件夹,代码如下:<?php $pat...

PHP对象转数组

PHP对象转数组

function objtoarr($obj){ $ret = array(); foreach($obj as $key =>$value){ if(gettype($value) == 'arr...

PHP高并发下数据库值更新的问题

PHP高并发下数据库值更新的问题

(1).创建数据库test ,创建表shop(字段id,total),商品id是1,商品总数10    (2).PHP模拟购买,商品数量大于0才能购买<?php //连接数据库 $con=mysqli_connect("192.168.2.18...

php使用swoole扩展推送消息

php使用swoole扩展推送消息

通过http推送消息给socket,socket服务再向客户端推送<?php /*  * Socket推送  * 请用守护进程方式启动php msgservice.php &   (socket只...

php 数组转换xml,php 数组转成xml,php数组转xml 函数

php 数组转换xml,php 数组转成xml,php数组转xml 函数

源码:特别适用于微信支付中通知微信支付网关function array2xml($arr, $level = 1) { $s = $level == 1 ? "<xml&g...