What is the easiest way to use the HEAD command of HTTP in PHP?

fuenfundachtzig picture fuenfundachtzig · Oct 9, 2009 · Viewed 10.8k times · Source

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.

Answer

PatrikAkerstrand picture PatrikAkerstrand · Oct 9, 2009

You can do this neatly with cURL:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");

// This changes the request method to HEAD
curl_setopt($ch, CURLOPT_NOBODY, true);

// grab URL and pass it to the browser
curl_exec($ch);

// Edit: Fetch the HTTP-code (cred: @GZipp)
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 

// close cURL resource, and free up system resources
curl_close($ch);