0

There is a response from the server contains a custom header "errcode":

Date: Wed, 24 Aug 2016 09:06:04 GMT
errcode: 1
Server: nginx/1.8.1
Connection: keep-alive
Transfer-Encoding: chunked

401 Unauthorized

How do I get by using PHP+CURL "errcode" value?

$ch = curl_init($url);
if ($ch) {
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$json = curl_exec( $ch );
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 $transfer = curl_getinfo($ch);
curl_close($ch);
}
echo $httpcode; ?> //200,401 etc
<pre><?=print_r($transfer);?></pre> //array, no contains "errcode"
Den Greyman
  • 97
  • 1
  • 1
  • 9

1 Answers1

0

cURL has a built-in feature that will pass every header of the response to a callback function. You need to use the option CURLOPT_HEADERFUNCTION:

curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header) {
    echo(trim($header) . PHP_EOL);
    return strlen($header);
});

Alternatively, if you do not want to use an anonymous function as a callback you may define a function and provide its name as a string parameter. The function accepts two arguments - the first one being the cURL resource itself, and the second one is the current header.

NB: The function is executed once per header, so you might want to store the results somewhere, in an array or a file, then search through that file for the content of the errcode header.

NB2: The function must return the length of the passed header (note the return strlen($header);). Otherwise cURL breaks.

kalatabe
  • 2,909
  • 2
  • 15
  • 24
  • Thank you! I managed to get all headers as strings. How do I get a "errcode" only? It is the latest in a string list. To turn every row in the array element, we need some separator, but it is not. – Den Greyman Aug 24 '16 at 11:58