In this paper, we describe the method of multithreading in PHP in conjunction with Curl. Share to everyone for your reference, as follows:
Multithreading is not supported by PHP, but we can use foreach to pseudo-multithreading, but this pseudo-multithreading speed is not necessarily more than a single-threaded to where to go, specifically to see an example.
When using the foreach statement to loop the image URL and to store all the pictures locally by using curl, there is a problem that can only be collected, and now the method of combining foreach and curl with multiple URL requests is summarized.
Method 1: Loop the request
$SR =array (Url_1,url_2,url_3), foreach ($sr as $k = = $v) {$curlPost = $v. '? f= incoming parameters '; $ch = Curl_init ($curlPost); curl_ Setopt ($ch, Curlopt_returntransfer, true); Get Data return curl_setopt ($ch, Curlopt_binarytransfer, true); Get Data back $data = curl_exec ($ch) when Curlopt_returntransfer is enabled; echo $k. ' # #: '. $data. ' <br> ';} Curl_close ($ch);
The above code requires special attention, curl_close must be placed in the end of the Foreach loop outside, if placed inside, will appear I mentioned above the multiple imgurl, can only collect a URL problem.
Method 2: Multithreaded Loops
<?phpmulti_threads_request ($nodes) { $mh = Curl_multi_init (); $curl _array = Array (); foreach ($nodes as $i = + $url) { $curl _array[$i] = Curl_init ($url); curl_setopt ($curl _array[$i], Curlopt_returntransfer, true); Curl_multi_add_handle ($MH, $curl _array[$i]); } $running = NULL; do { usleep (10000); Curl_multi_exec ($MH, $running); } while ($running > 0); $res = Array (); foreach ($nodes as $i = + $url) { $res [$url] = curl_multi_getcontent ($curl _array[$i]); } foreach ($nodes as $i = + $url) { curl_multi_remove_handle ($mh, $curl _array[$i]); } Curl_multi_close ($MH); return $res;} Print_r (multi_threads_request (Array (' http://www.php.cn ', ' http://tools.php.cn ',));
The main use of curl_multi_init () to implement multiple URL requests, but because PHP itself does not support multi-threading, so pseudo-multithreading speed is not necessarily faster than a single thread.
I hope this article is helpful to you in PHP programming.