Home >Backend Development >PHP Tutorial >PHP code example using curl to simulate multi-threaded requests

PHP code example using curl to simulate multi-threaded requests

不言
不言forward
2018-11-17 17:19:252197browse

The content of this article is about the code example of PHP using curl to simulate multi-threading to send requests. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The execution of each PHP file is single-threaded, but PHP itself can also use some other technologies to achieve multi-threaded concurrency, such as using the php-fpm process. Here, curl is used to simulate multi-threaded sending requests. PHP's curl multi-threading obtains content by continuously calling curl_multi_exec. Here is a demo to simulate a curl multi-threaded concurrent operation.

//设置缓冲为0(也可以去php.ini设置)
ini_set('output_buffering', 0);
//打开输出缓冲区
ob_start();
//设置一个空数组
$curl_Arr=[];
//这里模拟20次请求
for($i=0;$i<20;$i++){
    //开启curl连接
    $curl_Arr[$i]=curl_init("http://XXXX/test.php");
    //CURLOPT_RETURNTRANSFER 设置为1表示稍后执行的curl_exec函数的返回是URL的返回字符串,而不是把返回字符串定向到标准输出并返回TRUE;
    curl_setopt($curl_Arr[$i],CURLOPT_RETURNTRANSFER,1);
}

//创建批处理cURL句柄
$mh = curl_multi_init();

foreach($curl_Arr as $k => $ch){
    //curl句柄入栈增加
    curl_multi_add_handle($mh,$ch);
}
$active = null;
while(count($curl_Arr)>0){
    //发起curl_multi请求
    @curl_multi_exec($mh,$active);
    foreach($curl_Arr as $k => $ch){
        //获取句柄的返回值
        if($result[$k]= curl_multi_getcontent($ch)){
            //输出结果
            echo "$result[$k]\n";
            ob_flush();
            //把被释放的数据发送到浏览器
            flush();
            //关闭该句柄
            curl_multi_remove_handle($mh,$ch);
            unset($curl_Arr[$k]);
        }
    }
}
//关闭ouput_buffering机制
ob_end_flush();
//关闭"curl_mulit"句柄
curl_multi_close($mh);

I created a requested php page on the server and named it test.php, with the following content

1 sleep(10);
2 echo &#39;seccess&#39;;exit;

indicates the following statement after waiting for ten seconds.

Then I executed the program on the command line and the results were as follows:

In the above code, curl_multi_getcontent is called by looping through the $curl_Arr array to query whether there is data. If there is data, output and delete elements until the number of elements in the $curl_Arr array reaches 0.

This simulated multi-thread implementation achieves this function by using curl's curl_multi series of functions. As for the introduction to the use of this series of functions, you can search a lot on Baidu. No explanation will be given here.

The above is the detailed content of PHP code example using curl to simulate multi-threaded requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete