cURL retrieve only header without doing HEAD

Keywords´╝Ü php curl

Question: 

So I am trying to retrieve only headers using cURL with the following:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);

The problem is that while trying to get headers of large file the script uses all the memory. I would like to avoid getting also the body and I have tried to use:

curl_setopt($ch, CURLOPT_NOBODY, true);

The problem is that this issues a HEAD request instead of GET. And some website retrun an error when you request with HEAD.

Is there any way with curl to retrieve only header without doing HEAD request?

Answers: 

First, don't use CURLOPT_RETURNTRANSFER as that's the option that makes it keep the entire response in memory.

Then, two options:

A) use a write callback and make that abort the transfer as soon as the first byte of the body is returned. There's a write callback example in the PHP.net docs.

B) use CURLOPT_RANGE and ask for only the first byte to be retrieved, 0-0. This avoids the write callback but has the downside that not all HTTP servers and URLs will acknowledge it.

You could use get_headers(). By default get_headers uses a GET request to fetch the headers. And you could also modify that by using stream_context_set_default()

$headers = get_headers('http://example.com');

More Info: PHP: get_headers