Need to track PC down times using PHP ping and display time down D:HH:MM

自作多情 提交于 2019-12-24 00:15:01

问题


I currently have this code, which runs as a ph that works to let me know if the pc's are pinging:

    <!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="30">
</head>
<body>

<h1>PC Test Ping Status</h1>

<?php
$host="10.161.10.98";
exec("ping -c 2 " . $host, $output, $result);
if ($result == 0)
echo "<p>p2 On-Line</p>";
else
echo "<p>p2 Off-Line !</p>";

$host="10.161.10.125";
exec("ping -c 2 " . $host, $output, $result);
if ($result == 0)
echo "<p>p3 On-Line</p>";
else
echo "<p>p3 Off-Line!</p>";

?> 


</body>
</html>

I want to track the time since the last successful ping if the pc isn't pinging.


回答1:


Here is an example using a text file, as requested. A few notes:

  1. For simplicity, I suggest using CURL instead of exec as it should be a lot faster and more reliable. This checks for the HTTP status code "200" which means it returned a valid request.
  2. You will need to make sure your text file/s have the appropriate read & write permissions.
  3. I've updated this answer to also address your other question.

The initial text file in this example is named data.txt and contains the following:

p1|google.com|
p2|yahoo.com|
p2|amazon.com|

The following code will cycle through each server in the list, and update the records with the latest date if it's online.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="30">
</head>
<body>

<h1>PC Test Ping Status</h1>

<?php

function ping($addr) {
    $ch = curl_init($addr);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //get response code
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code === 200) {
        return true;
    }

    return false;
}

$file = 'data.txt';
$servers = array_filter(explode("\n", file_get_contents($file)));
foreach ($servers as $key => $server) {
    list($sname, $saddr, $suptime) = explode('|', $server);
    if (ping($saddr)) {
        echo "<p>$sname is online</p>";
        $date = new DateTime();
        $suptime = $date->format('Y-m-d H:i:s');
    } else {
        echo "<p>$sname is offline since: ";
        if (trim($suptime) !== '') {
            echo $suptime . '</p>';
        } else {
            echo 'unknown</p>';
        }
    }
    $servers[$key] = implode('|', array($sname, $saddr, $suptime)) . "\n";
}
file_put_contents($file, $servers);

?> 


</body>
</html>


来源:https://stackoverflow.com/questions/41681077/need-to-track-pc-down-times-using-php-ping-and-display-time-down-dhhmm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!