Tim Igoe's Web Design, Development and Hosting Blog

PHP – Check Service Status

Posted on by Tim Igoe

Got multiple servers? Want to know they are still up by looking at once place? Want to give your users an easy to see status page?

A quick way to test if a server or service is up is to try connecting to it, if you can connect, you can assume that the server is still online. While this method isn’t perfect it works most of the time.


function serverStatus($host, $port)
{
// Try first connection, quick timeout
if ($Conn = fsockopen($host, $port, $error, $errorStr, 1)) // Connected ok first time
$retVal = 1;
// Try a longer connection
if ($Conn = fsockopen($host, $port, $error, $errorStr, 10)) // Connected ok - server must be slow
$retVal = 2;

if ($Conn)
fclose($Conn);
else // Must have failed
$retVal = 3;

return $retVal;
}

This method will return a value that gives an indication of how well the server is working,
the return values are
1 = server up and answering fast
2 = server up and running slow
3 = server down

This entry was posted in PHP and tagged , , . Bookmark the permalink.

Leave a Reply