PHP: Get Headers using cURL

How to get headers using cURL in PHP? We can know the health of a web page without visiting a link. We can get the information about link status whether is returning response 200 or it is moved it somewhere else or it is dead.


<?php
/**
*	Script to check link validity
*
*	@author Satya Prakash
*
*/
$links = array();
$links[] = 'http://www.satya-weblog.com/2007/04/dynamically-populate-select-list-by.html';
$links[] = 'http://www.satya-weblog.com/2009/11/setting-site-restriction-to-google-ajax-search-api.html';
$links[] = 'http://www.satya-weblog.com/2009/08/jquery-ajax-example-of-select-values.html';
$links[] = 'http://www.satya-weblog.com/2007/05/php-file-upload-and-download-script.html';
$links[] = 'http://www.satya-weblog.com/2008/02/header-for-xml-content-in-php-file.html';
$links[] = 'http://www.satya-weblog.com/2010/02/add-input-fields-dynamically-to-form-using-javascript.html';
$links[] = 'http://www.satya-weblog.com/2007/06/javascript-show-hide-div-p-input-or-any.html';
$links[] = 'http://www.satya-weblog.com/2007/05/php-and-javascript-cookie.html';
$links[] = 'http://goo.gl/IbKHP';
foreach ($links as $link) {
	$ch = curl_init($link);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 1); // return header
	curl_setopt($ch, CURLOPT_NOBODY, 1); // no body return. it will faster
	$linkHeaders = curl_exec($ch);
	$curlInfo = curl_getinfo($ch);
	curl_close($ch);
	switch(intval($curlInfo['http_code']/100)) {
		case 2:
			// Status is 2xx. Page is in correct health
			$status = 'OK';
			break;
		case 3:
			// Status is 3xx. It means redirection
			// Page has moved
			$status = 'MOVED';
			if (preg_match('@^Location: (.*)$@m', $linkHeaders, $matches)) {
				$location = trim($matches[1]);
				$status .= ": $location";
			}
			break;
		default:
			// any error
			$status = "Error: $curlInfo[http_code]";
			break;
	}
	echo "<p>
			$link: $status
		</p>
		";
}
?>

Output from the above cURL code:

Comments are open for an year period. Please, write here on Facebook page.