Returning header as array using Curl

Returning header as array using Curl

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Returning header as array using Curl

Extracting response headers in PHP via cURL is a common requirement when handling file downloads or API responses that rely on metadata like Content-Disposition. The specific challenge arises when you need to parse the filename embedded in the attachment parameter of that header. While curl_getinfo() provides high-level status codes and sizes, it does not return the raw header string list. To access the full header set—including custom fields—you must intercept the stream during execution using CURLOPT_HEADERFUNCTION.

The core issue developers often face is managing the state of headers outside the callback scope. In your current implementation, you are appending strings directly to $this->_headers within the readHeader function. While this technically captures the raw lines (e.g., "Content-Disposition: attachment; filename="report.pdf"\r\n"), parsing these manually requires splitting each line and handling the key-value extraction logic yourself.

A more robust approach involves leveraging cURL's built-in ability to return headers as an associative array if configured correctly, or ensuring your custom callback returns the correct status to keep streaming while capturing data. However, CURLOPT_HEADERFUNCTION always receives raw strings. To convert this into a usable PHP array structure without writing a full parser inside the callback, you can accumulate the raw lines and process them after execution.

Here is how you might refactor the wrapper class logic to handle this cleanly:

curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
// Enable header mode to capture headers even if we don't print them
curl_setopt($this->_ch, CURLOPT_HEADER, true); 
curl_setopt($this->_ch, CURLOPT_POST, 1);
curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $this->_postData);
curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);

// Define the callback to capture headers
curl_setopt($this->_ch, CURLOPT_HEADERFUNCTION, [$this, 'readHeader']);

$response = curl_exec($this->_ch);
$info = curl_getinfo($this->_ch);

// Parse the accumulated raw headers into an associative array
$rawHeaders = $this->_headers; // Assuming this is populated in readHeader
$headersArray = [];

foreach ($rawHeaders as $line) {
    if (empty($line)) continue;
    
    [$key, $value] = explode(':', trim($line), 2);
    $headersArray[$key] = trim($value);
}

// Now you have access to the filename easily
$filename = $headersArray['Content-Disposition'] ?? null;

There is a critical trade-off here regarding CURLOPT_HEADER. By setting it to true, cURL includes headers in the response buffer returned by curl_exec(). If your code relies on $this->_response containing only the body, you must strip the header block before processing or ensure you separate them. In the example above, we assume the _headers property captures the raw lines while the response object retains the full stream for further inspection if needed.

The readHeader function must strictly return the number of bytes read in the header to indicate success. Returning false stops the transfer prematurely. Your original code used array_push, which is correct, but ensure you are not modifying the array while iterating if you were to switch strategies later.

One significant pitfall is that cURL headers can contain multiple lines for a single field (e.g., Set-Cookie). A simple explode approach assumes single-line headers. For most file download scenarios involving Content-Disposition, this assumption holds true, but keep in mind that complex multi-value headers require more sophisticated parsing logic if you decide to support them.

If you are working within the Laravel ecosystem, note that while native cURL wrappers offer low-level control, frameworks like Laravel provide helpers that abstract these details. However, when specific header manipulation is required for file handling logic, understanding the raw cURL mechanism remains essential. For more advanced HTTP client needs in PHP, libraries like guzzlehttp/guzzle often simplify header retrieval into associative arrays automatically without manual parsing callbacks.

Ultimately, capturing headers via CURLOPT_HEADERFUNCTION gives you total control but demands careful state management outside the callback. By accumulating raw strings and converting them to an associative array post-execution, you gain a reliable method to extract filenames from Content-Disposition headers without relying on incomplete metadata provided by curl_getinfo().

Our network