I would like to send the HEAD command of the Hypertext Transfer Protocol to a server in PHP to retrieve the header, but not the content or a URL. How do I do this in an efficient way?
The probably most common use-case is to check for dead web links. For this I only need the reply code of the HTTP request and not the page content.
Getting web pages in PHP can be done easily using file_get_contents("http://...")
, but for the purpose of checking links, this is really inefficient as it downloads the whole page content / image / whatever.
As an alternative to curl you can use the http context options to set the request method to
HEAD
. Then open a (http wrapper) stream with these options and fetch the meta data.see also:
http://docs.php.net/stream_get_meta_data
http://docs.php.net/context.http
Even easier than curl - just use the PHP
get_headers()
function which returns an array of all header info for any URL you specify. And another real easy way to check for remote file existence is to usefopen()
and try to open the URL in read mode (you'll need to enable allow_url_fopen for this).Just check out the PHP manual for these functions, it's all in there.
It seems like pear has it:
http://pear.php.net/manual/en/package.http.http.head.php
You can do this neatly with cURL: