PHP website monitoring script

Here’s a handy script (called “sPing”) to monitor any number of sites and ensure that they return a pleasant status code (200 or 304). The script will silently access each of the URLs in the array. Any that return something nasty like a 403, 404, 500, or 503 will be output to the console along with the particular status code.

sping.php
[sourcecode language='php']

/* -------- Configuration -------- */

define('VERSION', '1.0');

define('USERAGENT', 'sPing/'.VERSION);
define('TIMEOUT', 10); // seconds

$sites = array(
'http://www.site1.com',
'http://www.site2.com',
'http://www.site3.com',
);

/* ------------------------------- */

if ( ! function_exists('curl_init')) { die("cURL is not available and is required.n"); }

$ch = curl_init();

$options = array(
CURLOPT_USERAGENT => USERAGENT,
CURLOPT_TIMEOUT => TIMEOUT,
CURLOPT_VERBOSE => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FRESH_CONNECT => true
);

curl_setopt_array($ch, $options);

foreach($sites as $site)
{
curl_setopt ($ch, CURLOPT_URL, $site);
$output = curl_exec($ch);

$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($status != 200 && $status != 304)
{
echo $site.” returned “.$status.”n”;
}
}
[/sourcecode]

You can customize the maximum allowed timeout (in seconds) and the user agent used when making the request. I use a unique user agent so I can track and exclude requests from this script in web server logs & statistics.

This script works best when run periodically via cron and piping the output to mail with the -e parameter. This tells mail only to send an e-mail if the message body is not null (meaning that one of the sites is acting up, the script produced output, and we want to know about it).

./sping.php | /usr/bin/mail -e -s "[`hostname`] Abnormal HTTP statuses" alerts@mydomain.com

Lastly, while you CAN run this script on the same server where the sites live (for catching things like syntax errors introduced by your team mate, hacking up files at 4 AM, or memory issues that might cause your sites to blank screen), it makes more sense to run this on a second, stable server with 24/7 connectivity in case the server completely crashes. It’s most effective to monitor from the view of the public (the “visitor” or the “customer”).

Missing something useful? Let me know how this script can be improved!