使用PHP创建ping正常运行时间服务 [英] Creating a ping uptime service with PHP
问题描述
我有一个可以在其上使用PHP的服务器,以及一个可以从Internet ping通的路由器.我想编写一个PHP脚本,该脚本每5分钟将ping发送一次到路由器,结果如下:
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:
- 如果ping成功,则不会发生任何事情.
- 如果ping操作失败,则等待几分钟,如果仍然失败,它将向我的电子邮件地址发送一次警告.
- 路由器再次可ping通后,它会发送一封电子邮件,表明一切正常.
这可以用PHP完成吗?如何?有人有一个小的 PHP文件吗?
Could this be done with PHP? How? Does anybody has a small PHP file that does this?
推荐答案
下面,我写了一个简单的PHP脚本,它可以满足您的要求.它将对服务器执行ping操作,将结果记录到文本文件(打开"或关闭"),然后根据先前的结果是打开还是关闭发送电子邮件.
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.
要使其每五分钟运行一次,您需要配置一个cron作业以每五分钟调用一次PHP脚本. (许多共享的网络主机允许您设置cron作业;请查阅主机提供商的文档以了解操作方法.)
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";
}
这篇关于使用PHP创建ping正常运行时间服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!