: This article describes how to send http requests in batches by phpcurl. For more information about PHP tutorials, see. Introduction: in Android4.0 development, Http requests cannot be executed in the main process and must be executed in the thread. The reason is that the Http interface response time may block the main process event listening (for. Net development, this is also true ). However, since PHP does not have the concept of multithreading, how can we 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 used to simulate the request. the code is very simple. the sleep time is controlled through the get parameter time.
$s_time=intval($_GET['time']);sleep($s_time);echo 'hello';
The following code uses curl_init only:
$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;
The execution time is about 15 seconds, which is the total sleep time. now, let's take a look at the time when curl_multi_init is used.
$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;
The result is only five seconds, even if the maximum http request execution time.
Note: We can see many people on the blog reflect the high CPU usage of curl_multi_init. In fact, you can add usleep to solve this problem. Because, if the data does not return curl_multi_exec, it will continue to run, consuming CPU resources.
The above introduces php curl to send http requests in batches, including some content, and hope to be helpful to friends who are interested in PHP tutorials.