Jump to content

Using cURL for a HEAD request


Arancaytar

Recommended Posts

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/".

[code=php:0]
$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);
$head=curl_exec($ch);
var_dump($head);
curl_close($ch);[/code]



[url=http://php.net/manual/en/function.curl-exec.php]curl_exec[/url] only returns true - even though it should return the entire response since I set RETURNTRANSFER to 1.

Any ideas?
Link to comment
https://forums.phpfreaks.com/topic/22220-using-curl-for-a-head-request/
Share on other sites

You can use CURLOPT_NOBODY option to send a HEAD request and CURLOPT_HEADER to retrieve the headers in the output. [url=http://www.php.net/curl_setopt]curl_setopt()[/url]

[code]
$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;
[/code]

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.
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...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.