Jump to content

Archived

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

Arancaytar

Using cURL for a HEAD request

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?

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites

×

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.