Home » PHP

PHP Uptime check

24 November 2008 No Comment

I found a useful script in PHP that can be used for checking uptime of a server. It can be useful for checking when the servers have a such a significant load that pages can’t be displayed. The benefit or running it locally is that I can configure the script to perform failover functionality if necessary. Online uptime services are good too, but most of them aren’t free. Maybe I should force the server to show a failwhale when the site gets too busy… j/k :D

Here’s the link to the script.
http://www.programmingtalk.com/showthread.php?t=34999


// the URL you want to keep tabs on
$url = 'http://www.somewebsite.com';

// if not available, send email
if ( url_exists( $url ) === FALSE )
{
$to = 'my@email.com';
$subj = $url . ' is down!';
$msg = $url . ' was tested at ' . date( 'Y-m-d H:i:s' ) . ' and was inaccessible.';
@mail( $to, $subj, $msg );
}

/**
* url_exists()
* Checks for the validity of a given URL
*
* @param string The http[s] URL you're checking for
* @return bool TRUE if online; FALSE if not; NULL if not an http(s):// URL
*/
function url_exists( $strURL = NULL )
{
if ( !preg_match( '/^http(s?):\/\//i', $strURL, $m ) )
return NULL;
@$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $strURL );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback' );
curl_setopt( $ch, CURLOPT_FAILONERROR, 1 );
curl_setopt( $ch, CURLOPT_TIMEOUT, 5 );
// https?
if ( $m[1] == 's' )
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
@curl_exec( $ch );
$intReturnCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );
return ( $intReturnCode == 200 OR $intReturnCode == 302 OR $intReturnCode == 304 ) ? TRUE : FALSE;
}

?>

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.