Getting response header in PHP cURL request

In my PHP page, I am sending a cURL request to another page. I am getting the response as:


HTTP/1.1 200 OK
Date: Sat, 20 Dec 2008 10:54:25 GMT
Content-Length: 62
Content-Type: text/plain
Cache-control: private

<?xml version="1.0"?>
<A>
    <B>SitePoint</B>
    <C>Forum</C>
</A>

How can I get only the header part of this response? i.e.,


HTTP/1.1 200 OK
Date: Sat, 20 Dec 2008 10:54:25 GMT
Content-Length: 62
Content-Type: text/plain
Cache-control: private

Actual requirement is to get the header part and the response string i.e., HTTP/1.1 200 OK. I am assuming that the first line in the response(header) will always contain the response string. Is my assumption is correct?

You can use curl_getinfo to return the http code:

<?php
$ch = curl_init('http://yoururl/');
curl_setopt($ch, CURLOPT_HEADER, 1);
$c = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE);

To get only the headers use CURLOPT_NOBODY. And yes, the status line is sent before the header fields (by specification).

Hi Guys, Thanks for the quick response.

@arkinstall

If I use this, I will get only Response code(200) only. But I need complete response status(HTTP/1.1 200 Ok).

@registrant

If I have to use this, I need to send two requests, one is for getting headers and one is for getting body content. I don’t think that I can do this when working with a page that updates database.

Is there anyway to get header length so that I can get that part from the response.

I misread your first post, thinking you wanted to retrieve the headers only, but I see you were asking how to extract them from the response.

You can explode the response at the header/content boundary:


 
list($header, $body) = explode("\\r\
\\r\
", $response, 2);

Or you can use curl_getinfo():


 
// ...[curl code]...
$info = curl_getinfo($ch);
curl_close($ch);
$header = substr($response, 0, $info['header_size']);
$body = substr($response, -$info['download_content_length']);

Edit: Then to get the status line:

$status = strtok($header, "\\r\
");

It is working. But, sometimes, the value of download_content_length is 0.

And for some POST and PUT requests I am getting HTTP/1.1 100 Continue header first and then getting the POST request headers and body. Is there any way that we can avoid this HTTP/1.1 100 Continue in the cURL response?