您可以使用exec()-function执行shell命令ping,如下例所示:
<?php
function GetPing($ip=NULL) {
if(empty($ip)) {$ip = $_SERVER['REMOTE_ADDR'];}
if(getenv("OS")=="Windows_NT") {
$ping=explode(",", $exec);
return $ping[1];//Maximum = 78ms
}
else {
$exec = exec("ping -c 3 -s 64 -t 64 ".$ip);
$array = explode("/", end(explode("=", $exec )) );
return ceil($array[1]) . 'ms';
}
}
echo GetPing();
?>
Run Code Online (Sandbox Code Playgroud)
资料来源:http://php.net/manual/en/function.exec.php
我想您想要的是:
const PING_REGEX_TIME = '/time(=|<)(.*)ms/';
const PING_TIMEOUT = 10;
const PING_COUNT = 1;
$os = strtoupper(substr(PHP_OS, 0, 3));
$url = 'www.google.com';
// prepare command
$cmd = sprintf('ping -w %d -%s %d %s',
PING_TIMEOUT,
$os === 'WIN' ? 'n' : 'c',
PING_COUNT,
escapeshellarg($url)
);
exec($cmd, $output, $result);
if (0 !== $result) {
// something went wrong
}
$pingResults = preg_grep(PING_REGEX_TIME, $output); // discard output lines we don't need
$pingResult = array_shift($pingResults); // we wanted just one ping anyway
if (!empty($pingResult)) {
preg_match(PING_REGEX_TIME, $pingResult, $matches); // we get what we want here
$ping = floatval(trim($matches[2])); // here's our time
} else {
// something went wrong (mangled output)
}
Run Code Online (Sandbox Code Playgroud)
这是一个单次ping仅获取ms的示例,但很容易对其进行调整以获取所需的内容。您要做的就是使用正则表达式,超时和计数常量。
您可能还想根据操作系统调整正则表达式(或添加更多),因为Linux ping将提供与Windows格式不同的结果。