PHP using Curl_multi To achieve the example of multithreading acquisition _php example

Source: Internet
Author: User

Two days a customer has customized a login free module, because in the module needs to involve a lot of picture download problem, considering the performance problem, so specially wrote a Curl_multi remote collection of Web page function, to facilitate later use, It is not expected to use the original single-threaded curl function to foreach, the performance comparison is obvious. Also get my blog 10 different pages, curl_multi:4.5246081352234,file_get_contents:33.001797914505, nearly 8 times times the efficiency, imagine if in the attachment more cases, Performance difference is more obvious, I hope to help you!

Copy Code code 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 {
& nbsp;               $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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.