Skip to content

Instantly share code, notes, and snippets.

@thagxt
Last active June 28, 2017 22:11
Show Gist options
  • Save thagxt/bb2849c4d34a1231ea94 to your computer and use it in GitHub Desktop.
Save thagxt/bb2849c4d34a1231ea94 to your computer and use it in GitHub Desktop.
php check headers status going thru all page statuses
<?php
/* @ http://stackoverflow.com/a/12628971 */
function getHttpResponseCode_using_getheaders($url, $followredirects = true){
// returns string responsecode, or false if no responsecode found in headers (or url does not exist)
// NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings))
// if $followredirects == false: return the FIRST known httpcode (ignore redirects)
// if $followredirects == true : return the LAST known httpcode (when redirected)
if(! $url || ! is_string($url)){
return false;
}
$headers = @get_headers($url);
if($headers && is_array($headers)){
if($followredirects){
// we want the the last errorcode, reverse array so we start at the end:
$headers = array_reverse($headers);
}
foreach($headers as $hline){
// search for things like "HTTP/1.1 200 OK" , "HTTP/1.0 200 OK" , "HTTP/1.1 301 PERMANENTLY MOVED" , "HTTP/1.1 400 Not Found" , etc.
// note that the exact syntax/version/output differs, so there is some string magic involved here
if(preg_match('/^HTTP\/\S+\s+([1-9][0-9][0-9])\s+.*/', $hline, $matches) ){// "HTTP/*** ### ***"
$code = $matches[1];
return $code;
}
}
// no HTTP/xxx found in headers:
return false;
}
// no headers :
return false;
}
//
if (getHttpResponseCode_using_getheaders($country_url, $followredirects = true) == '404') {
echo "404";
} else {
echo "200 or other statuses";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment