Extracting Headers from cURL Responses and Managing State
When you initialize a curl session, execute a request, and capture the raw response string using curl_exec, the resulting data is a single concatenated blob. This blob contains the HTTP headers followed immediately by the body content. In your specific scenario, you are receiving an Authorization header containing a JWT token alongside other metadata like Content-Type and Server information. The challenge lies in parsing this mixed string to isolate the specific header value without relying on external libraries that might obscure the underlying logic.
The standard approach involves leveraging the built-in PHP functions explode() and preg_match(). Since HTTP headers are separated from the body by a double line break (\r\n\r\n), you can split the response string at this delimiter to isolate the header section first. Once you have the header-only string, you can iterate through it or use a regular expression to extract the specific key-value pair you need.
Here is a practical implementation that demonstrates how to parse the raw curl_exec output:
$response = curl_exec($client);
if ($response === false) {
throw new Exception('cURL error: ' . curl_error($client));
}
// Split headers and body based on the double line break separator
[$headerSection, $body] = explode("\r\n\r\n", $response, 2);
// Use a regex pattern to find the Authorization header specifically
// The pattern looks for "Authorization:" followed by any characters until a space or end of line
preg_match('/^Authorization:\s*(.+)$/m', $headerSection, $matches);
if (isset($matches[1])) {
$token = trim($matches[1]);
// Store in the session cookie as requested
setcookie('auth_token', $token, time() + 3600, '/', '', true, true);
} else {
throw new Exception('Authorization header not found in response.');
}
This method is robust because it doesn't depend on the order of headers or the presence of other data. The regular expression /^Authorization:\s*(.+)$/m specifically targets lines starting with Authorization, allowing for optional whitespace after the colon. The m flag ensures that if the header happens to be a multi-line value (though rare for Authorization, it is possible for other headers), the pattern still matches correctly within the context of the header block.
However, there is a significant trade-off here: you are responsible for parsing and validating the string manually. If the server response format changesâsuch as moving from HTTP/1.1 to HTTP/2 where headers are frame-based rather than line-based in the raw streamâor if the separator changes slightly, your parser will break. Additionally, relying on explode("\r\n\r\n") assumes a strict adherence to the HTTP/1.x protocol where headers and body are strictly separated by that exact sequence.
A more idiomatic and safer approach in modern PHP is to use the CURLOPT_HEADERFUNCTION callback. Instead of retrieving the entire raw response string, you can intercept the header stream as it arrives. This allows you to write each header line directly into a dedicated variable or array as soon as it is received, completely bypassing the need to parse the body and headers together later.
$headerBuffer = '';
$callback = function ($ch, $header) use (&$headerBuffer) {
global $header;
// Append to the buffer.
// You can check if the line starts with 'Authorization' here to extract immediately.
if (stripos($header, 'Authorization:') !== false) {
// Extract value manually or push to a specific variable
preg_match('/^Authorization:\s*(.+)$/i', $header, $matches);
if ($matches) {
$token = trim($matches[1]);
setcookie('auth_token', $token, time() + 3600, '/', '', true, true);
}
}
return strlen($header); // Return length to continue receiving data
};
curl_setopt($client, CURLOPT_HEADERFUNCTION, $callback);
$response = curl_exec($client);
Using a callback function offers better performance for large responses because it processes headers in real-time without loading the full response into memory before processing. It also decouples header extraction from body parsing, making your code more resilient to changes in the response body size or structure.
If you are building larger applications where manual string manipulation feels cumbersome, consider using a dedicated HTTP client library like Guzzle. These libraries abstract away the raw curl mechanics and provide clean methods to access headers via $response->getHeaderLine('Authorization'). While this adds a dependency, it significantly reduces the risk of regex errors and makes the codebase more maintainable. For high-volume applications, understanding how to handle cookies securely is vital; ensure that any token stored in a cookie is marked as HttpOnly and Secure to prevent client-side script access and transmission over unencrypted connections.
Whether you choose manual parsing with curl_exec or implement a header callback, the core principle remains the same: isolate the data you need before mixing it with the rest of the response stream.
