Home > Backend Development > PHP Tutorial > php curl sends http requests in batches

php curl sends http requests in batches

WBOY
Release: 2016-07-29 09:14:21
Original
1438 people have browsed it

Introduction: In Android 4.0 development, sending Http requests is no longer allowed to be executed in the main process and must be executed in a thread. The reason is that the response time of the Http interface may block the event monitoring of the main process (the same is true for .Net development). However, since PHP does not have the concept of multi-threading, how to efficiently execute multiple http requests in PHP? The answer is to use curl_multi_init, so I did an experiment.

The following is the http interface that simulates the request. The code is very simple. The sleep time is controlled by the parameter time passed in by get.

$s_time=intval($_GET['time']);
sleep($s_time);
echo 'hello';
Copy after login

Next, just use curl_init. The code is as follows:

$start=microtime(true);
for($i=1;$i<=5;++$i)
{
	$ch=curl_init("http://test.binbin.com/curl/test.php?time={$i}");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_exec($ch);
}
$end=microtime(true);
echo $end-$start;
Copy after login

The execution time is about 15 seconds, which is the sum of all sleep times. Now, let’s take a look at the time using curl_multi_init

$start=microtime(true);
$ch_list=array();
$multi_ch=curl_multi_init();
for($i=1;$i<=5;++$i)
{
	$ch_list[$i]=curl_init("http://test.binbin.com/curl/test.php?time={$i}");
	curl_setopt($ch_list[$i], CURLOPT_RETURNTRANSFER, true);
	curl_multi_add_handle($multi_ch, $ch_list[$i]);
}
$running=false;
do {
        usleep(10000);
	curl_multi_exec($multi_ch, $running);
}while ($running>0);

$end=microtime(true);
echo $end-$start;
Copy after login
The result is only 5 seconds clock, even the execution time of the longest http request.

Postscript: I saw many people reporting on blogs the problem of excessive CPU usage using curl_multi_init. In fact, it can be solved by adding usleep. Because if the data is not returned, curl_multi_exec will continue to execute, consuming CPU resources.

The above introduces php curl to send http requests in batches, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template