PHP Script to monitor server uptime

Tue Oct 31 23:09:44 2006 EST (-0500 GMT)

Recently at work I needed to create a script to check a server’s response time. This was for the purposes of tracking and graphing the response time (or lack of) of a server that was acting up when most people had better things to do. I also wanted to send out an E-Mail to my cell phone when the server went down.

responcegraph.png

A cursory look around the net indicated there was nothing I could directly grab and deploy, so I created my own script in PHP. This script can be run from the web or from the command line.

To use this script create another file and include this file with the absolute file name (absolute names are important on the command line).
Include example:
include(‘/var/www/html/monitor/server_monitor.php’);

You can then call the timer_check function.
This function takes following peramitors, you must set a URL, all other peramitors are optional.

  • url: ie ‘http://news.google.ca’
  • time limit: default is 10 seconds
  • E-Mail Address: If it takes longer than the time limit who do we call? This should be an array.
  • Should we print anything to the screen, or just send E-Mail if ther’s a problem? true/false
  • Maximum attempts: By default this script makes 10 attemps in a row and averages the results, you can set it to one 1 or even 100

Example of a script that might be called google.php:

〈?PHP
include('/var/www/html/monitor/server_monitor.php');
$url = 'http://google.ca/';
$email = array('nobody@localhost','[email protected]);
timer_check ($url,10,$email); ?>

If you wanted to make this a cron job (scheduled task under Linux/OSX) here’s two examples that run every 10 minutes.
These examples keep a log file called server_uptime that can be imported into something like MS Excel and graphed:

*/10 * * * * cd /var/www/html/monitor; php -f google.php >> server_uptimeThis example has to be run as root, but the negative nice value makes sure your evaluating the connetion to the remote
server, not your own server’s load.

*/10 * * * * cd /var/www/html/monitor; nice -n -2 php -f google.php >> server_uptime

You can get the source code at: ctlet.brocku.ca/monitor/server_monitor.phps

Comments are closed.