<?PHP
header
('Content-Type: text/plain'); //Set proper output format
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1

if (strstr($_SERVER['SCRIPT_URL'],'server_monitor.php')) {
    print 
"This script checks server response time and can send E-Mail when a server appears to be down.
    
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('$_SERVER[SCRIPT_FILENAME]');
    
You can then call the timer_check function.
This function takes following permitters, you must set a URL, all other permitters 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 attempts 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:

include('$_SERVER[SCRIPT_FILENAME]');

\$url = 'http://google.ca/';
\$email = array('nobody@localhost','mymobilephone@mycellphone.provider);

timer_check (\$url,10,\$email);
    
    
If you wanted to make this a cron job here's two examples that run every 10 minutes.
These examples keep a log file that can be imported into something like MS Excel and graphed:

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


This 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

"
;
    
}


/* Server check function */

/**
 * Executes the user signup form
 *
 * @param $url String with URL to check, include the protocal - required
 * @param $tlimit Integer of the amount of time to wait for the URL to load before we declare a panic and send an E-Mail. l - default is 10
 * @param $email An array of E-Mail address to send E-Mail to if loading the URL takes longer than the time limit. - default is just nobody@localhost
 * @param $print bolean - Print the out put to the screen, or just send E-Mail if there is a proble,. - default is to prinit to screen
 * @param $max_tries Integer - Number of times to connect and then average. - default is to prinit to screen
*/

function updatedb ($url,$time,$down) {
    if (
$GLOBALS['db'] == true) { //added to log info in DB
        
$connect mysql_connect("localhost""monitor""");    
        
mysql_select_db("monitor");
        if (
$down == true$sql 'INSERT INTO `monitor`.`log` (`timestamp`, `location`, `time`) VALUES (NOW(), \''.$url.'\', \'100.0\');';
        else 
$sql 'INSERT INTO `monitor`.`log` (`timestamp`, `location`, `time`) VALUES (NOW(), \''.$url.'\', \''.$time.'\');';
        
mysql_query($sql);
        
        
$sql 'SELECT `timestamp` , `status` FROM `track` WHERE CONVERT(`track`.`location` USING utf8) = \''.$url.'\' LIMIT 1;';
        
$result mysql_query($sql);
        
$row mysql_fetch_assoc($result);

        if (
$down == true && $row['status'] == 'up') {            
            
$sql 'UPDATE `monitor`.`track` SET `timestamp` = NOW(), `status` = \'down\' WHERE CONVERT(`track`.`location` USING utf8) = \''.$url.'\' LIMIT 1;';
            
mysql_query($sql);
            }
        elseif (
$down == false && $row['status'] == 'down') {
            
$sql 'UPDATE `monitor`.`track` SET `timestamp` = NOW(), `status` = \'up\' WHERE CONVERT(`track`.`location` USING utf8) = \''.$url.'\' LIMIT 1;';
            
mysql_query($sql);
            }
        
mysql_close ($connect);
    }
    
}


function 
timer_check ($url,$tlimit 10,$email 'nobody@localhost',$print true,$max_tries 10$port null) { //main function to do timing
    
$headers "From: nobody@$_SERVER[HOSTNAME] \r\n" .
    
'X-Mailer: PHP/' phpversion();
    
$time 0;
    
    
$attempts = array();
    for(
$i 0;$i <= $max_tries$i++) {
        
$attempts[$i] = timer_check_only($url,true,$port);
    }
    
    foreach (
$attempts as $value) {
        
$time += $value;
    }
    
$time $time $max_tries;
    
    if (
$time $tlimit) {
        
$down true;
        if (
$time 100) {
            
$time timer_check_only($url,false); // one last try, what's up?
            
$message ="The server at $url is down.    $time\n";
        }
        else 
$message ="The server at $url $port is not responding within $tlimit seconds. \t$time\n";

        if (
$GLOBALS['db'] == true) {
            
$connect mysql_connect("localhost""monitor""C8S4M7LawnFHVn2U");    
            
mysql_select_db("monitor");

            
$sql 'SELECT * FROM `track` WHERE CONVERT(`track`.`location` USING utf8) = \''.$url.'\' LIMIT 1;';
            
$result mysql_query($sql);
            
$status_row mysql_fetch_assoc($result);
            
            
$a explode(' ',$status_row['email']);
            
$last explode(':',$a[1]);
            
$go_mail false;
            if (
$last[0] != date('G')) {
                
$go_mail true;
                
$sql 'UPDATE `monitor`.`track` SET `email` = NOW() WHERE CONVERT(`track`.`location` USING utf8) = \''.$url.'\' LIMIT 1;';
                
mysql_query($sql);
            }
             foreach (
$email as $value) {
                       
$where $_SERVER['SCRIPT_URI'];
                       if (
strlen($where) < 1$where $_SERVER['SCRIPT_FILENAME'].' on '.$_SERVER['HOSTNAME'];
                       if (
strrpos($value'cell') == false && strrpos($value'mobile') == false$message ."\nThis script runs from $where";
            
                    
$message .= "\nStatus has been ".$status_row['status'].' since '.$status_row['timestamp'].'.';
                                    
                    if (
$go_mail == true) {
                        
mail($value'Server Status is '.$status_row['status'],$message $headers);
                        
$sql 'UPDATE `monitor`.`track` SET `email` = NOW() WHERE CONVERT(`track`.`location` USING utf8) = \''.$url.'\' LIMIT 1;';
                        
mysql_query($sql);
                    }
                    
                    
mysql_close ($connect);
                }    
        }
        else {
             foreach (
$email as $value) {
                   
$where $_SERVER['SCRIPT_URI'];
                   if (
strlen($where) < 1$where $_SERVER['SCRIPT_FILENAME'].' on '.$_SERVER['HOSTNAME'];
                   if (
strrpos($value'cell') == false && strrpos($value'mobile') == false$message ."\nThis script runs from $where";
                
mail($value'Server Status',$message $headers);
            }
        }

        if (
$GLOBALS['db'] == true) {
            
updatedb($url,$time,true);
            
        }
       print 
date('r')."    ERROR: ".$message;
    }
    else   {
        if (
$print == true) print date('r')."    $url responded within $tlimit seconds \t$time\n";
    }

    if (
$GLOBALS['db'] == trueupdatedb($url,$time,false);

}

function 
timer_check_only($url,$nofail true,$port null) { //main function to do timing

    
ini_set('user_agent','Mozilla/4.0 (Linux i686; en;)  PHP/' phpversion()); //user agent is honest, you may want a fake one

    
$time_start microtime(true);
    if (isset(
$port)) {
        
$ch curl_init();    // initialize curl handle
        
curl_setopt($chCURLOPT_PORT$port);            //Set the port number
        
curl_setopt($chCURLOPT_URL$url); // set url to post to
        
$file = @curl_exec($ch);
        
curl_close($ch);
    }
    else 
$file = @fopen ($url"r");

    
$time_end microtime(true);
    
$time $time_end $time_start;

    @
fclose($file);
    if (!
$file && $nofail == true$time 100;

return 
$time;
}


?>