In PHP, sometimes I want to send an HTTP request to a remote site just to look at the response headers, so I declare it all manually and use the fsock_open()
function. However, this goes much slower than calling file_get_contents()
with a remote URL (which loads the whole page content). Why is this? Is there a good alternative way to get just the response headers (to check if a page returns a 404 error, for example) that works as fast as file_get_contents()
?
Have you just tried using curl? You can get back the headers and also the content, if desired.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/
2008120122 Firefox/3.0.5";
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
This will chase redirects, which isn't always desired.
Look at http://php.net/manual/en/function.curl-getinfo.php to see what you get back in $info
.
You can try just doing a HEAD request instead of a GET (the CURLOPT_NOBODY
option), but I have run into problems with some servers that deny HEADs for some reason.