如何判断cURL句柄是否超时?

时间:2011-01-01 13:22:57

标签: php curl

我有一个脚本,通过curl_multi _ *

连接到大约100个网址

我使用curl_multi_getcontents来获取每个句柄的内容,但是如何确定连接是否成功?

1 个答案:

答案 0 :(得分:0)

我不知道你是如何实现curl_multi的,但是这个基于php.net/manual/en/function.curl-multi-info-read.php的示例#1的脚本可能有所帮助。注释表示相应的更改。

$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 

**/

如果传输超时,则该URL的消息应该是与CURLE_OPERATION_TIMEOUTED(int 28)对应的消息,类似于“操作超时。根据条件达到指定的超时时间”({{3 }})。