2011-09-10 67 views
9

我有,我可以使用PHP的服務器,並且可以從互聯網上ping通路由器。我想編寫一個PHP腳本,每5分鐘發送一次ping到路由器,結果如下:創建平安服務的正常運行時間與PHP

  • 如果ping成功,則不會發生任何事情。
  • 如果ping失敗,那麼它會等待幾分鐘,如果它仍然失敗,它發出了一個警告,我的E-mail地址一次。
  • 路由器再次ping後,它會發送一封電子郵件,說它沒問題。

難道這是用PHP做了什麼?怎麼樣?有沒有人有一個 PHP文件,這樣做?

+0

會不會使用cron作業音質更好? – ajreal

回答

9

下面我寫了一個簡單的PHP腳本,做你的要求。它會ping一個服務器,將結果記錄到一個文本文件(「up」或「down」),並根據前一個結果是否啓動發送一封電子郵件。

讓它每隔五分鐘運行,你需要配置一個cron作業來調用PHP腳本每五分鐘。 (許多共享的網絡主機允許你設置cron作業;諮詢您的託管服務提供商的文檔,以找出如何)

<?php 

//Config information 
$email = "[email protected]"; 
$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"; 
} 
+0

PHP中沒有原生的ping功能,所以來看看http://stackoverflow.com/questions/1239068/ping-site-and-return-result-in-php如果你嘗試使用這個腳本...或者當然使用像http://www.nagios.org/ – CodeReaper

+2

@CodeReaper這樣的監控系統腳本已經包含了這個ping功能。 – Nick

+0

壞了,在我的iPad上衝浪,並沒有想到嘗試向下滾動。 – CodeReaper

3

我個人使用Pingdom的服務,如果它能夠從互聯網上ping通和正在運行的HTTP服務器上。沒有必要真的深入寫一個特殊的腳本。

+1

試圖監控50多個網站時,它可能很昂貴。 –

0

以及據我所知,你不能用PHP創建一個cronjob,但你能做的就是用crontab

this所以你能夠ping到所需的主機也可以改爲運行

exec("ping 1.2.3.4")

在腳本