PHP虚拟多线程Curl访问外部网络

<?php

/**
 * 虚拟多线程Curl
 *
 * @param        $urls array 网址列表
 * @param string $cookie
 *
 * @return array
 */
function duo_curl(array $urls, string $cookie = ''): array
{
    $ua    = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36';
    $queue = curl_multi_init();
    $map   = [];
    foreach ($urls as $url) {
        $ch = curl_init();
        
        if ($cookie) {
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        
        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            ['t:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTQyNjk4MTAsIm5iZiI6MTY2MzE2NzYxMCwiaWF0IjoxNjYzMTY1ODEwLCJqdGkiOiJDTTpjYXRfbWF0Y2g6bHQxMjM0NTYiLCJvcGVuX2lkIjoiIiwidWlkIjo0NjI1MTY1NSwiZGVidWciOiIiLCJsYW5nIjoiIn0.9Xr13c-YAOvfsSUpJ7G8FMzImXhPDKB0RABNJS1wxlo']
        );
        curl_setopt($ch, CURLOPT_REFERER, 'https://servicewechat.com/wx141bfb9b73c970a9/17/page-frame.html');
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOSIGNAL, true);
        curl_multi_add_handle($queue, $ch);
        $map[(int)$ch] = $url;
    }
    $responses = [];
    do {
        while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM) {
        }
        if ($code != CURLM_OK) {
            break;
        }
        while ($done = curl_multi_info_read($queue)) {
            //            $info = curl_getinfo($done['handle']);
            $error                                 = curl_error($done['handle']);
            $results                               = curl_multi_getcontent($done['handle']);//返回内容
            $responses[$map[(int)$done['handle']]] = compact('error', 'results');
            curl_multi_remove_handle($queue, $done['handle']);
            curl_close($done['handle']);
        }
        if ($active > 0) {
            curl_multi_select($queue, 0.5);
        }
    } while ($active);
    curl_multi_close($queue);
    return $responses;
}

$urls = [];

for ($i = 1; $i <= 5; $i++) {
    $urls[] = "https://www.baidu.com/?f=" . $i;
}
echo '<pre>';
//print_r($urls);

$get = duo_curl($urls);
print_r($get);

 

版权声明:
作者:tianya
链接:https://tya.zone/p/42.html
来源:天涯博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
PHP虚拟多线程Curl访问外部网络
<?php /** * 虚拟多线程Curl * * @param $urls array 网址列表 * @param string $cookie * * @return array */ function duo_cur……
<<上一篇
下一篇>>