0

我听说过很多关于 php 的 cURL 多线程,但从未真正尝试过它,我发现理解它的实际工作原理有点困难。任何人都可以将其转换为curl_multi?

$path1 = array("path1", "path2", "path3"); //example
$path2 = array("path1", "path2", "path3"); //example
$opt = curl_init($path1);
curl_setopt($opt, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($opt);
curl_close($opt);
file_put_contents($path2, $content);

我真正想做的是从数组中下载多个文件path 1path 2using curl_multi.

4

2 回答 2

2

这是一个很好的项目开始......

https://github.com/jmathai/php-multi-curl

我正在使用 curl multi,它确实很棒。我正在使用它来制作更快的推送通知。

https://github.com/Krutarth/FlashSnsPns

于 2013-10-27T02:54:08.543 回答
2

上述接受的答案已过时/错误,因此,必须对正确答案进行投票。

http://php.net/manual/en/function.curl-multi-init.php

现在,PHP 支持同时获取多个 URL。

有一个人写的很好的函数,http://archevery.blogspot.in/2013/07/php-curl-multi-threading.html

这是功能:

function runRequests($url_array, $thread_width = 4) {
$threads = 0;
$master = curl_multi_init();
$curl_opts = array(CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS => 5,
    CURLOPT_CONNECTTIMEOUT => 15,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_RETURNTRANSFER => TRUE);
$results = array();

$count = 0;
foreach($url_array as $url) {
    $ch = curl_init();
    $curl_opts[CURLOPT_URL] = $url;

    curl_setopt_array($ch, $curl_opts);
    curl_multi_add_handle($master, $ch); //push URL for single rec send into curl stack
    $results[$count] = array("url" => $url, "handle" => $ch);
    $threads++;
    $count++;
    if($threads >= $thread_width) { //start running when stack is full to width
        while($threads >= $thread_width) {
            usleep(100);
            while(($execrun = curl_multi_exec($master, $running)) === -1){}
            curl_multi_select($master);
            // a request was just completed - find out which one and remove it from stack
            while($done = curl_multi_info_read($master)) {
                foreach($results as &$res) {
                    if($res['handle'] == $done['handle']) {
                        $res['result'] = curl_multi_getcontent($done['handle']);
                    }
                }
                curl_multi_remove_handle($master, $done['handle']);
                curl_close($done['handle']);
                $threads--;
            }
        }
    }
}
do { //finish sending remaining queue items when all have been added to curl
    usleep(100);
    while(($execrun = curl_multi_exec($master, $running)) === -1){}
    curl_multi_select($master);
    while($done = curl_multi_info_read($master)) {
        foreach($results as &$res) {
            if($res['handle'] == $done['handle']) {
                $res['result'] = curl_multi_getcontent($done['handle']);
            }
        }
        curl_multi_remove_handle($master, $done['handle']);
        curl_close($done['handle']);
        $threads--;
    }
} while($running > 0);
curl_multi_close($master);
return $results;
}

你可以使用它。

于 2016-05-19T12:32:01.390 回答