This article mainly introduces the example of using CURL_MULTI to implement multi-thread collection in PHP. CURL_MULTI can perform concurrent access to HTTP, you can refer to a user who has customized a login-free publishing module in the next two days. this is because many image download problems are required in the module. considering the performance problems, therefore, I wrote a function called CURL_MULTI to remotely collect web pages for future use. it is estimated that the previous single-thread curl function will not be used for foreach in the future. The performance comparison is obvious. I also got ten different webpages from my blog, curl_multi: 4.5246081352234, file_get_contents: 33.001797914505, which is nearly eight times more efficient. if there are more attachments, the more obvious the performance difference is, I hope it will help you!
The code is as follows:
<? Php
$ Text = remote (array ('http: // www.jb51.net/', 'http://www.baidu.com /'));
Print_r ($ text );
Function remote ($ urls ){
If (! Is_array ($ urls) or count ($ urls) = 0 ){
Return false;
}
$ Curl = $ text = array ();
$ Handle = curl_multi_init ();
Foreach ($ urls as $ k => $ v ){
$ Nurl [$ k] = preg_replace ('~ ([^: \/\.] + )~ Ei ', "rawurlencode (' \ 1')", $ v );
$ Curl [$ k] = curl_init ($ nurl [$ k]);
Curl_setopt ($ curl [$ k], CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ curl [$ k], CURLOPT_HEADER, 0 );
Curl_multi_add_handle ($ handle, $ curl [$ k]);
}
$ Active = null;
Do {
$ Mrc = curl_multi_exec ($ handle, $ active );
} While ($ mrc = CURLM_CALL_MULTI_PERFORM );
While ($ active & $ mrc = CURLM_ OK ){
If (curl_multi_select ($ handle )! =-1 ){
Do {
$ Mrc = curl_multi_exec ($ handle, $ active );
} While ($ mrc = CURLM_CALL_MULTI_PERFORM );
}
}
Foreach ($ curl as $ k => $ v ){
If (curl_error ($ curl [$ k]) = ""){
$ Text [$ k] = (string) curl_multi_getcontent ($ curl [$ k]);
}
Curl_multi_remove_handle ($ handle, $ curl [$ k]);
Curl_close ($ curl [$ k]);
}
Curl_multi_close ($ handle );
Return $ text;
}