我有一台可以使用PHP的服务器和一台可以从互联网上ping的路由器。我想编写一个PHP脚本,每5分钟向路由器发送一次ping,结果如下:
可以用PHP完成吗?怎么样?有没有人有小 PHP文件来执行此操作?
答案 0 :(得分:9)
下面我写了一个简单的PHP脚本来完成你的要求。它ping服务器,将结果记录到文本文件(“向上”或“向下”),并根据先前结果是上升还是下降发送电子邮件。
要让它每五分钟运行一次,您需要配置一个cron作业,每五分钟调用一次PHP脚本。 (许多共享的Web主机允许您设置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";
}
答案 1 :(得分:3)
我个人使用Pingdom服务,如果它可以从互联网上ping并在其上运行HTTP服务器。无需真正深入编写特殊脚本。
答案 2 :(得分:0)