Can PHP cURL retrieve response headers AND body in a single request?

Can PHP cURL retrieve response headers AND body in a single request?

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

Stefan Bogdanescu

Founder & Senior Architect

Can PHP cURL retrieve response headers AND body in a single request?

Developers often face a specific dilemma when interacting with external APIs: they need the response headers to determine content types, status codes, or rate-limiting information, but they also require the actual payload. The instinctive solution proposed by many online resources is CURLOPT_HEADER. While this option technically appends headers to the output stream, it forces you to parse a concatenated string containing both metadata and data. This approach is inefficient and prone to errors if the header parsing logic fails or if the boundary between headers and body is mishandled.

The goal is to capture both elements without issuing a separate HEAD request, which would double network latency and violate the requirement for a single round-trip. Fortunately, PHP's cURL extension provides a cleaner mechanism that avoids manual string manipulation entirely.

The CURLOPT_HEADERFILE Approach

The most robust way to handle this in native PHP is to utilize CURLOPT_HEADERFILE. Instead of appending headers to the body stream, you direct cURL to write the headers to a separate file specified by this option. This keeps the output buffer clean, containing only the response body.

Here is how you implement it:

$ch = curl_init();
$url = 'https://api.example.com/data';

// Set up the request
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Returns body as string instead of outputting directly
curl_setopt($ch, CURLOPT_HEADERFILE, '/tmp/headers.txt'); // Write headers to a file

$responseBody = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

// Read the headers from the file if needed
$rawHeaders = file_get_contents('/tmp/headers.txt');

curl_close($ch);

By decoupling the header storage from the body retrieval, you eliminate the need for custom parsing logic that attempts to split a single string. This is particularly useful when dealing with complex headers or when you need to pass headers to another component of your application without risking corruption of the payload.

The CURLOPT_HEADER Alternative and Its Trade-offs

If creating temporary files is not feasible due to security constraints or filesystem limitations, the standard approach involves enabling CURLOPT_HEADER. As noted in common discussions, this option returns both headers and body as a single string when using CURLOPT_RETURNTRANSFER.

To extract the body from this concatenated stream, you typically need the header size. You can retrieve this using curl_getinfo($ch, CURLINFO_HEADER_SIZE). Once you have the byte count of the headers, you can use substr() to slice the response string and separate the two components programmatically.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true); // Include headers in output

$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

$headersOnly = substr($response, 0, $headerSize);
$bodyOnly = substr($response, $headerSize);

curl_close($ch);

While this method avoids filesystem I/O, it introduces a parsing step that must be handled carefully. If the server response includes headers in an unexpected format or if there is a mismatch between CURLINFO_HEADER_SIZE and the actual header length (which can happen with certain proxies or malformed responses), the split may yield incorrect data.

Security and Best Practices

From a security perspective, relying on manual string splitting of raw HTTP responses is generally discouraged unless absolutely necessary. Raw headers often contain directives that could be exploited if blindly executed, although PHP's curl_exec context typically mitigates immediate risks like header injection attacks during parsing. However, the primary risk with the concatenated approach is data integrity; treating binary or multi-part content as a simple string can lead to subtle bugs when calculating offsets.

For high-performance applications where minimizing I/O overhead is critical, the in-memory splitting method using CURLOPT_HEADER combined with CURLINFO_HEADER_SIZE remains a viable option. It avoids disk writes entirely, making it suitable for environments where file system latency is a bottleneck or where temporary files are restricted.

Ultimately, the choice depends on your specific constraints regarding memory usage and filesystem access. If you are building a library that needs to be universally compatible, returning headers and body as separate objects or arrays is often superior to returning a concatenated string, as it encapsulates the complexity of parsing within the function's logic rather than exposing it to the caller.

Our network