Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get status text from failed curl response in PHP

Tags:

php

curl

How can I get the status text (not status code) using curl in PHP?

HTTP/1.1 400 Unsupported voice
...

In the above sample HTTP response, I can get the status code with CURLINFO_RESPONSE_CODE.

But what I am interested in is the status text Unsupported voice. I couldn't find a CURLINFO constant for status text.

The only option I can think of is to set CURLOPT_HEADER and parse the response. In case of success response, the response body contains binary data. Hence I am a bit reluctant to use str_* functions on it.

Is there a better solution?

like image 907
Joyce Babu Avatar asked Dec 22 '25 18:12

Joyce Babu


1 Answers

I have managed to resolve it using CURLOPT_HEADERFUNCTION. But this does not work with HTTP/2.

<?php

$statusText = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://stackoverflow.com/');
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$statusText) {
    echo $header;
    if (is_null($statusText)) {
        preg_match('~^HTTP/[^ ]+ \d+ (.*)$~', $header, $match);
        $statusText = $match[1];
    }
    
    return strlen($header);
});
$response = curl_exec($ch);

echo $statusText;
like image 58
Joyce Babu Avatar answered Dec 24 '25 09:12

Joyce Babu