Creating a ping uptime service with PHP

LanceBaynes picture LanceBaynes · Sep 10, 2011 · Viewed 9.8k times · Source

I have a server that I can use PHP on and a router that can be pinged from the Internet. I want to write a PHP script that sends a ping to the router every 5 minutes with the following results:

  • If the ping succeeds, then nothing would happen.
  • If the ping fails, then it waits a few minutes, and if it still fails it sends a warning to my e-mail address once.
  • After the router is pingable again it sends an e-mail that it's OK.

Could this be done with PHP? How? Does anybody has a small PHP file that does this?

Answer

Nick picture Nick · Sep 10, 2011

Below I've written a simple PHP script that does what you ask. It pings a server, logs the result to a text file ("up" or "down"), and sends an email depending whether the previous result was up or down.

To get it to run every five minutes, you'd need to configure a cron job to call the PHP script every five minutes. (Many shared web hosts allow you to set up cron jobs; consult your hosting provider's documentation to find out how.)

<?php 

//Config information
$email = "[email protected]";
$server = "google.com"; //the address to test, without the "http://"
$port = "80";


//Create a text file to store the result of the ping for comparison
$db = "pingdata.txt";

if (file_exists($db)):
    $previous_status = file_get_contents($db, true);
else:
    file_put_contents($db, "up");
    $previous_status = "up";
endif;

//Ping the server and check if it's up
$current_status =  ping($server, $port, 10);

//If it's down, log it and/or email the owner
if ($current_status == "down"):

    echo "Server is down! ";
    file_put_contents($db, "down");

    if ($previous_status == "down"):
        mail($email, "Server is down", "Your server is down.");
        echo "Email sent.";     
    endif;  

else:

    echo "Server is up! ";
    file_put_contents($db, "up");

    if ($previous_status == "down"):
        mail($email, "Server is up", "Your server is back up.");
        echo "Email sent.";
    endif;

endif;


function ping($host, $port, $timeout)
{ 
  $tB = microtime(true); 
  $fP = fSockOpen($host, $port, $errno, $errstr, $timeout); 
  if (!$fP) { return "down"; } 
  $tA = microtime(true); 
  return round((($tA - $tB) * 1000), 0)." ms"; 
}