在 PHP curl_multi 中,是否有等效于 curl_getinfo() 的方法来获取 curl_multi_exec() 的 HTTP 响应代码?

In PHP curl_multi, is there an equivalent to curl_getinfo() to fetch HTTP response codes for curl_multi_exec()?

使用 curl_getinfo(),您可以获取请求的响应代码: https://www.php.net/manual/en/function.curl-getinfo.php

$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE));

有函数 curl_multi_info_read(),但我认为它似乎并没有完全做同样的事情: https://www.php.net/manual/en/function.curl-multi-info-read.php

Contents of the returned array
Key:    Value:
msg The CURLMSG_DONE constant. Other return values are currently not available.
result  One of the CURLE_* constants. If everything is OK, the CURLE_OK will be the result.
handle  Resource of type curl indicates the handle which it concerns.

代码示例:

var_dump(curl_multi_info_read($mh));

输出如下:

array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(5) of type (curl)
}

而不是给出 HTTP 响应代码。有没有办法从这个返回的数组中获取 HTTP 响应代码?或者 curl_multi() 中的其他方式来获取响应代码?

您可以使用 curl_multi_select() as shown in the first example in curl_multi_info_read()。然后你可以使用 $info['handle'] 来获取所有请求的信息。

$urls  = [
    'http://www.cnn.com/',
    'http://www.bbc.co.uk/',
    'http://www.yahoo.com/'
];
$codes = [];

$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]);
}

do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
    while (false !== ($info = curl_multi_info_read($mh))) {
        //
        // here, we can get informations about current handle.
        //
        $url = curl_getinfo($info['handle'],  CURLINFO_REDIRECT_URL);
        $http_code = curl_getinfo($info['handle'], CURLINFO_HTTP_CODE);

        // Store in an array for future use :
        $codes[$url] = $http_code;
    }
} while ($active && $status == CURLM_OK);

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

// display results
print_r($codes);

输出:

Array
(
    [https://www.cnn.com/] => 301
    [https://www.bbc.co.uk/] => 302
    [https://www.yahoo.com/] => 301
)