Get response code, headers and contents from curl_exec

113 Views Asked by At

I can't seem to figure out a way to get response code, headers and contents from my curl_exec.

Here's my last attempt:

$url = '...';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CAINFO, 'PATH_TO_.cer');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HEADER, true); //ATTEMPT1
/*curl_setopt($curl, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$headers){ //ATTEMPT2
    $len = strlen($header);
    $header = explode(':', $header, 2);
    if (count($header) < 2){ // ignore invalid headers
        return $len;
    }
    $headers[strtolower(trim($header[0]))][] = trim($header[1]);
    print_r($headers);
    return $len;
});*/
$contents = curl_exec($curl);
curl_close($curl);

I tried ATTEMPT1 and ATTEMPT2

In the headers of my requests, there are plenty of fields such as rate limits that I need to retrieve every time, but I also need the response code and the content of the request.

EDIT: So far I found that I'd need to use ATTEMPT1 over ATTEMPT2 because the last one is just an handcrafted version I can't seem to understand that is getting rid of the response code in the header.

1

There are 1 best solutions below

0
On

You're looking for curl_getinfo()

For instance, to get the response code:

$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);