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:
Could this be done with PHP? How? Does anybody has a small PHP file that does this?
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";
}
I personally use the Pingdom service if it can be pinged from the internet and is running an HTTP server on it. No need to really go deep into writing a special script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With