Avatar ·

How to get HTTP response headers and response body in one request using PHP cURL?

Hello everyone! I'm writing a parser in PHP using cURL. I need to get not only the page content (response body), but also the HTTP headers (e.g., Content-Type, Status Code, Location on redirects).

\n\n

The problem is that when I use curl_exec(), I only get the response body. If I enable the option CURLOPT_HEADER => true, the result outputs everything together — both headers and body — and I have to parse them manually using explode(), which is very inconvenient.

\n\n

Here is my current code:

\n
$ch = curl_init('https://example.com');\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_HEADER, true);\n$response = curl_exec($ch);\ncurl_close($ch);\n\n// Have to hackishly split\n$header_size = curl_ge