Check site up or down using php
by Guna[ Edit ] 2012-07-23 18:53:03
Below function lets you to check a site is up or down. This function creates a connection using fsocket
function. Using http status code from the header we'll know the site is active or down. Have a look at the code.
function checkit($url)
{
$url = @parse_url($url);
if (!$url) return false;
$url = array_map('trim', $url);
$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
$path = (isset($url['path'])) ? $url['path'] : '/';
$path .= (isset($url['query'])) ? "?$url[query]" : '';
if (isset($url['host']) && $url['host'] != gethostbyname($url['host']))
{
$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
if (!$fp) return false;
fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
$headers = fread($fp, 4096);
fclose($fp);
if(preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers))
{
return true;
}
else
return false;
}
else
return false;
}
if(checkit("http://hiox.org"))
echo "This site is up";
else
echo "This site is down";