I'm attempting to use the PHP cURL lib to make a simple call to an API to retrieve data. I want to be able to store the response headers as well as the response body, and to do this I am using CURLOPT_HEADERFUNCTION
as follows:
$headers = [];
curl_setopt(
$cURLHandle,
CURLOPT_HEADERFUNCTION,
function ($cURLHandle, $header) use (&$headers) {
$pieces = explode(":", $header);
if (count($pieces) >= 2) $headers[trim($pieces[0])] = trim($pieces[1]);
}
);
But when I run the above code, it produces cURL error #23: Failed writing header
.
Why is this happening and how can I resolve this?
This is happening because the header length (in bytes) needs to be returned from the function you provide for CURLOPT_HEADERFUNCTION
.
I believe, although I am not sure of this, this is because PHP needs/wants to be able to report the length of the headers from curl_getinfo(...)
calls.
The fixed code would look something like the following:
$headers = [];
curl_setopt(
$cURLHandle,
CURLOPT_HEADERFUNCTION,
function ($cURLHandle, $header) use (&$headers) {
$pieces = explode(":", $header);
if (count($pieces) >= 2) $headers[trim($pieces[0])] = trim($pieces[1]);
return strlen($header); // <-- this is the important line!
}
);