用PHP创建ping正常运行时间服务


Creating a ping uptime service with PHP

我有一个可以使用PHP的服务器和一个可以从互联网ping通的路由器。我想写一个PHP脚本,每5分钟发送一个ping到路由器,结果如下:

  • 如果ping成功,那么什么都不会发生。
  • 如果ping失败,则等待几分钟,如果仍然失败,则向我的电子邮件地址发送一次警告。
  • 当路由器再次可以ping通后,它会发送一个电子邮件表示它是OK的。

这可以用PHP完成吗?如何?有人有小的 PHP文件吗?

下面我编写了一个简单的PHP脚本,可以满足您的要求。它ping服务器,将结果记录到文本文件("up"或"down"),并根据之前的结果是"up"还是"down"发送电子邮件。

要使它每五分钟运行一次,需要配置一个cron作业,每五分钟调用一次PHP脚本。(许多共享的网络主机允许你设置cron作业;请参考您的托管提供商的文档以了解如何。

<?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"; 
}

我个人使用Pingdom服务,如果它可以从互联网ping通,并在其上运行HTTP服务器。不需要真正深入编写一个特殊的脚本

据我所知,你不能用PHP创建cronjob,但你可以使用crontab

,这样你就可以ping到所需的主机,你也可以运行

exec("ping 1.2.3.4")