Creating a ping uptime service with PHP

冷暖自知 提交于 2019-12-18 12:28:40

问题


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?


回答1:


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 = "your@emailaddress.com";
$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"; 
}



回答2:


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.




回答3:


well as far as i know you can't create a cronjob with PHP , but what you can do is use crontab

and this so you will be able to ping to required host also you can run instead

exec("ping 1.2.3.4")

in your script



来源:https://stackoverflow.com/questions/7372780/creating-a-ping-uptime-service-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!