如何使用PHP在我的PING中获得往返时间

时间:2016-08-09 10:43:25

标签: php

所以我有这个代码,无论什么时候IP可以ping或者它,它都会选择绿线出现在我的屏幕上,反之则是红线。所以,如果该IP的往返时间为< 200然后它是绿色的,当它是> 250它是红色的。我怎样才能做到这一点? 任何人帮助我。谢谢。

<?php
$page = $_SERVER['PHP_SELF'];
$sec = 5;

function pingAddress($TEST) {
    $pingresult = exec("ping -c 1 $TEST", $output, $result);

    if ($result == 0) {
        echo "Ping successful!";
        echo "<pre>Your ping: $TEST</pre>";
        echo "<hr color = \"green\" width = 40%> GOOD";
    } else {
        echo "Ping unsuccessful!";
        echo "<pre>Your ping: $TEST</pre>";
        echo "<hr color = \"red\" width = 40%> BAD";
    }
}  
pingAddress("66.147.244.228");
?>

<html>
<head> 
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo   $page?>'">
</head>
<body> 
</body>
</html>

1 个答案:

答案 0 :(得分:0)

exec函数可以使用,但在首先将其声明为数组后,应该解析输出参数的内容。 即使你添加-c 1只发出一次ping,这也是推荐使用exec的方法。

define('RETRIES', 1);
define('PING_PATH', '/usr/bin/ping');

function pingAddress($IP)
{
    $output = array();
    exec(PING_PATH . " -c " . RETRIES . " $IP", $output);

    // generic way, even for one line. You can also do -c 4,
    // and preg_match will pick the first meaningful result.

    $output_string = implode("; ", $output); 

    /// adapt the regular expression to the actual format of your implementation of ping
    if (preg_match('/ time=\s+(\d+)ms/', $output_string, $bits)) {
        $rt_time = (int)$bits[1];

        if ($rt_time < 200) {
            // green business
        }
        else if ($rt_time > 250) {
            // red business
        }
        else {
            // default handler business (or not...)
        }
    }
    else {
        echo "Hum, I didn't manage to parse the output of the ping command.", PHP_EOL;
    }

}