Jump to content


Using cURL for a HEAD request

  • Please log in to reply
2 replies to this topic

#1 Arancaytar

  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 27 September 2006 - 08:08 AM

I can't figure out what I'm doing wrong here. The code block is intended to take the URL contained in $url, send a HEAD request and then print the header that comes back.

For this test, I set $url="http://www.google.com/".

$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST,"HEAD");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

curl_exec only returns true - even though it should return the entire response since I set RETURNTRANSFER to 1.

Any ideas?

#2 shoz

  • Staff Alumni
  • Advanced Member
  • 600 posts

Posted 27 September 2006 - 08:56 AM

You can use CURLOPT_NOBODY option to send a HEAD request and CURLOPT_HEADER to retrieve the headers in the output. curl_setopt()

$ch = curl_init();
$url = 'http://www.google.com/';

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$r = curl_exec($ch);
$headers =  explode("\r\n\r\n", $r);
$header = $headers[(count($headers) - 2)];
print $header;

I've noticed that in cases where there are redirects(note the CURLOPT_FOLLOWLOCATION), the header output includes all the previous headers as well. Which is why I've included the explode and $headers[(count...)] to retrieve the last header returned.

#3 Arancaytar

  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 27 September 2006 - 09:12 AM

Thanks a lot!

I still don't understand why the CUSTOMREQUEST thing doesn't seem to work, but I got headers with your method, and that's what counts.

One thing though: Will this fetch the whole page, thus increasing the amount of data actually transferred? At the volume I will be using it, this won't be a real problem, but still.

Edit: Okay, NOBODY will prevent the whole page from being fetched. So it appears to act exactly the same as a HEAD request.

Now I'm only wondering why you can't use customrequest for this...

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users