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

标签 php performance ping

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

  • 如果 ping 成功,则什么也不会发生。
  • 如果 ping 失败,它会等待几分钟,如果仍然失败,它会向我的电子邮件地址发送一次警告。
  • 在路由器再次可 ping 通后,它会发送一封电子邮件表示一切正常。

这可以用 PHP 完成吗?如何?有人有执行此操作的 PHP 文件吗?

最佳答案

下面我编写了一个简单的 PHP 脚本来执行您的要求。它对服务器执行 ping 操作,将结果记录到文本文件(“向上”或“向下”),并根据之前的结果是向上还是向下发送电子邮件。

要使其每五分钟运行一次,您需要配置一个 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"; 
}

关于php - 使用 PHP 创建 ping 正常运行时间服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7372780/

相关文章:

php - 试图让 Laravel 5 电子邮件工作

php - SQL 查询根据month_year 获取行

php - 使用 php 发布数据属性

jquery - 组合 $.css() 调用的性能改进?

c# - While 循环使用 Ping 命令

PHP MySQL UNION SELECT 未按预期方式工作

java - ThreadLocal 变量的性能

java - 使用 Java Scanner 库解析此内容的最有效方法是什么?

arrays - 通过主机阵列 ping 并在表中显示结果

c - 在 C 中 Ping 服务器