Skip to content

Instantly share code, notes, and snippets.

@liunian
Created February 21, 2012 08:25
Show Gist options
  • Save liunian/1875119 to your computer and use it in GitHub Desktop.
Save liunian/1875119 to your computer and use it in GitHub Desktop.
use curl to get headers if get_headers is unable to use
<?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>
";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment