2

With curl_getinfo(), you can fetch the response codes for a request: https://www.php.net/manual/en/function.curl-getinfo.php

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

There is the function curl_multi_info_read(), but I think it doesn't seem to quite do the same thing: 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.

The code example:

var_dump(curl_multi_info_read($mh));

Gives output like:

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

Instead of giving the HTTP response code. Is there a way to fetch the HTTP response code from this returned array? Or maybe some other way in curl_multi() to fetch the response codes?

Tristan
  • 1,561
  • 3
  • 18
  • 22

1 Answers1

2

YOu could use curl_multi_select() as shown in the first example in curl_multi_info_read(). Then you can use $info['handle'] to get information about all requests.

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

Output :

Array
(
    [https://www.cnn.com/] => 301
    [https://www.bbc.co.uk/] => 302
    [https://www.yahoo.com/] => 301
)
Syscall
  • 19,327
  • 10
  • 37
  • 52