note 102050 deleted from function.get-headers by danbrown
| From: | danbrown@php.net | Date: | Tue, 25 Jan 2011 13:58:21 +0000 |
| Subject: | note 102050 deleted from function.get-headers by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176292@lists.php.net to get a copy of this message | ||
Note Submitter: domwatson at live dot co dot uk
----
Was looking for something that checks a website to see if its OK but couldn't find a nice and
cheap solution. Looking through what Weboide and Nick said, I've combined the two into a
function.
The function below will return a response code and allow you to follow redirections as well to
handle those 301/302s
function get_http_response_code($url, $followRedirects = true) {
# Supress errors due to warnings on failure
$headers = @get_headers($url);
$responseCode = substr($headers[0], 9, 3);
if ($followRedirects){
foreach($headers as $header){
if ($header === 'HTTP/1.1 200 OK'){
$responseCode = '200';
break 1;
}
}
}
return $responseCode;
}
# Follow redirection
$code = get_http_response_code('http://www.konoro.co.uk/', true);
// string '200' (length=3)
var_dump($code);
# Do not follow redirection, get first response code
$code = get_http_response_code('http://www.konoro.co.uk/', false);
// string '301' (length=3)
var_dump($code);
Cheers, Dom