开发者

How can I determine if the cURL handle timed out?

开发者 https://www.devze.com 2023-02-02 04:18 出处:网络
I have a scri开发者_JS百科pt that connects to around 100 URLs with curl_multi_* I use curl_multi_getcontents to grab the contents of each handle, but how can I determine if the connection was success

I have a scri开发者_JS百科pt that connects to around 100 URLs with curl_multi_*

I use curl_multi_getcontents to grab the contents of each handle, but how can I determine if the connection was successful?


I don't know how you're implementing curl_multi, but this script, based on example #1 at php.net/manual/en/function.curl-multi-info-read.php, might help. Relevent changes are indicated by the comments.

$urls = array(
   "http://example.com/",
   "http://qwe.rtyuiop.com/",
   "http://php.net/"
);

$mh = curl_multi_init();

foreach ($urls as $i => $url) {
    $conn[$i] = curl_init($url);
    curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($mh, $conn[$i]);
    // Set up info array:
    $multi_info[(integer) $conn[$i]]['url'] = $url;
}

do {
    $status = curl_multi_exec($mh, $active);
    $info = curl_multi_info_read($mh);
    if (false !== $info) {
        // Add connection info to info array:
        if (!$info['result']) {
            $multi_info[(integer) $info['handle']]['error'] = 'OK';
        } else {
            $multi_info[(integer) $info['handle']]['error'] = curl_error($info['handle']);
        }
    }
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);

foreach ($urls as $i => $url) {
    $res[$i] = curl_multi_getcontent($conn[$i]);
    curl_close($conn[$i]);
}

// Display result messages:
foreach ($multi_info as $each) {
    echo $each['url'] . ' => ' . $each['error'] . "\n";
}

/**
Output:

http://example.com/ => OK
http://qwe.rtyuiop.com/ => Could not resolve host: qwe.rtyuiop.com; Host not found
http://php.net/ => OK 

**/

If a transfer times out, then the message for that url should be the one corresponding to CURLE_OPERATION_TIMEOUTED (int 28), something like "Operation timeout. The specified time-out period was reached according to the conditions" (curl.haxx.se/libcurl/c/libcurl-errors.html).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号