【问题标题】:Crontab who ping website using PHP on Debian server在 Debian 服务器上使用 PHP ping 网站的 Crontab
【发布时间】:2013-12-12 16:17:54
【问题描述】:

我制作了 ping 网站的 php 脚本,如果我有答案,我什么也不做,否则我发送电子邮件警报。 这是我的代码:

function urlExists($url=NULL)  
{  
    if($url == NULL) return false;  
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    $data = curl_exec($ch);  
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);  
    if($httpcode>=200 && $httpcode<300){  
        return true;  
    } else {  
        return false;  
    }  
}
$url = 'http://www.website.com/';



if(urlExists($url) == true)
{
   exit('Website OK'."\n");
} else {

    $headers ='From: "Sembot"<noreply@website.com>'."\n"; 
    $headers .='Reply-To: noreply@website.com'."\n"; 
    $headers .='Content-Type: text/html; charset="iso-8859-1"'."\n"; 
    $headers .='Content-Transfer-Encoding: 8bit'; 

    foreach ($destinataire as $dest) {
        echo 'Website DOWN'."\n";
        if(mail($dest, 'Sembot - Website DOWN', 'Website DOWN', $headers)) { echo 'email...'; }
    }

}

当我在浏览器或控制台上执行此文件时,消息是“网站正常”,因为网站现在正常。但是当我创建一个每 5 分钟执行一次我的脚本的 crontab 时,我每 5 分钟收到一封电子邮件,但网站并没有死......你知道为什么吗?

【问题讨论】:

  • cron 默认将 cron 作业的输出通过电子邮件发送给作业的所有者。如果您不想让“ok”消息被邮寄,那么不要在该代码路径中执行任何输出。

标签: php cron debian crontab ping


【解决方案1】:

我已经使用这个 python 脚本一年了。工作正常,你需要知道的一切才能让它在自述文件中工作 https://github.com/bloodwithmilk25/ping-script

【讨论】:

    【解决方案2】:

    我看到您的 200 旁边有一个 >=。每次都如此,因为您的 300 小于 300 并且大于或等于 200。

    而不是这个:

    if($httpcode>=200 && $httpcode<300){  
        return true;  
    } else {  
        return false;  
    }  
    

    试试这个:

    if($httpcode > 200 && $httpcode < 300){  
        return true;  
    } else {  
        return false;  
    }  
    

    我只是删除了等号。

    【讨论】:

    • 据我了解,他在寻找一个范围没有?
    • 但是 200 是成功的,>200 只会在非常边缘的情况下发生。合适的范围是 200-299,而不是 201-299。也就是说,这个问题和这段代码无关,这个改动会引入一个新的bug。
    猜你喜欢
    • 2016-01-16
    • 2011-07-07
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 2018-04-16
    • 1970-01-01
    相关资源
    最近更新 更多