Skip to content

Instantly share code, notes, and snippets.

@Alexander-Pop
Forked from thagxt/url-check.php
Last active February 1, 2019 16:56
Show Gist options
  • Save Alexander-Pop/8efb5a627e43705ddc8049dfb61387d7 to your computer and use it in GitHub Desktop.
Save Alexander-Pop/8efb5a627e43705ddc8049dfb61387d7 to your computer and use it in GitHub Desktop.
php check headers status going thru all page statuses #php #url
<?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";
}
<?php
// check if URL exists
function checkUrl($url) {
// Simple check
if (!$url) { return FALSE; }
// Create cURL resource using the URL string passed in
$curl_resource = curl_init($url);
// Set cURL option and execute the "query"
curl_setopt($curl_resource, CURLOPT_RETURNTRANSFER, true);
curl_exec($curl_resource);
// Check for the 404 code (page must have a header that correctly display 404 error code according to HTML standards
if(curl_getinfo($curl_resource, CURLINFO_HTTP_CODE) == 404) {
// Code matches, close resource and return false
curl_close($curl_resource);
return FALSE;
} else {
// No matches, close resource and return true
curl_close($curl_resource);
return TRUE;
}
// Should never happen, but if something goofy got here, return false value
return FALSE;
}
// checking
if (checkUrl($country_url) == false) {
echo "404 not found";
echo $search;
} else {
echo "200 OK";
echo $country_url;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment