威凡软文网全力打造:网页编程、软件开发编程、平面设计、服务器端开发、操作系统等在线学习平台!学编程,上威凡软文网!
PHP教程>> PHP基础 PHP技巧 PHP实例 PHP文摘 PHP模板 PHP总结
当前位置:首页 > PHP教程 > PHP实例
上一节 下一节
 PHP 获取 ping 时间的实现方法

PHP 可以通过exec函数执行shell命令,来获取ping时间。

代码示例:

echo 'PHP_INT_MAX : ' . PHP_INT_MAX . "<br><br>";
 
$ip = '115.29.237.28';    // IP地址
 
if (PATH_SEPARATOR==':')  // linux
{
  echo 'I am linux' . "<br><br>";
   
  exec("ping -c 3 -w 5 $ip", $info);
  echo 'linux info : ' . "<br>";
  print_r($info);
   
  $ping_time_line = end($info);
  echo '<br><br>ping_time_line : ' . $ping_time_line . "<br><br>";
   
  $ping_time = explode("=", $ping_time_line)[1];
  $ping_time_min = explode("/", $ping_time)[0] / 1000.0;
  $ping_time_avg = explode("/", $ping_time)[1] / 1000.0;
  $ping_time_max = explode("/", $ping_time)[2] / 1000.0;
   
  echo $ping_time_min . " " . $ping_time_avg . " " . $ping_time_max . "<br><br>";
   
}
else             // windows
{
  echo 'I am windows' . "<br><br>";
 
  exec("ping -c 3 -w 5 $ip", $info);
  echo 'windows info : ' . "<br>";
  print_r($info);
   
  $info_time = end($info);
  echo '<br><br>info_time : ' . $info_time . "<br><br>";
}

运行结果:

PHP_INT_MAX : 9223372036854775807

I am linux

linux info :

Array ( [0] => PING 115.29.237.28 (115.29.237.28) 56(84) bytes of data. [1] => 64 bytes from 115.29.237.28: icmp_seq=1 ttl=52 time=26.1 ms [2] => 64 bytes from 115.29.237.28: icmp_seq=2 ttl=52 time=27.5 ms [3] => 64 bytes from 115.29.237.28: icmp_seq=3 ttl=52 time=25.2 ms [4] => [5] => — 115.29.237.28 ping statistics — [6] => 3 packets transmitted, 3 received, 0% packet loss, time 2002ms [7] => rtt min/avg/max/mdev = 25.280/26.339/27.590/0.970 ms )

ping_time_line : rtt min/avg/max/mdev = 25.280/26.339/27.590/0.970 ms

0.02528 0.026339 0.02759

 获取Ping时间封装成函数

function ping_time($ip) {
  $ping_cmd = "ping -c 3 -w 5 " . $ip;
  exec($ping_cmd, $info);
  $ping_time_line = end($info);
   
  $ping_time = explode("=", $ping_time_line)[1];
  $ping_time_min = explode("/", $ping_time)[0] / 1000.0;
  $ping_time_avg = explode("/", $ping_time)[1] / 1000.0;
  $ping_time_max = explode("/", $ping_time)[2] / 1000.0;
   
  $result = array();
  $result['ping_min'] = $ping_time_min;
  $result['ping_avg'] = $ping_time_avg;
  $result['ping_max'] = $ping_time_max;
   
  print_r($result);
}
 
ping_time('115.29.237.28');

运行结果:

Array ( [ping_min] => 0.025497 [ping_avg] => 0.025947 [ping_max] => 0.026753 )

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望通过本文能帮助到大家,谢谢大家对本站的支持!


申明:本文章由威凡软文网编辑整理并发布,如文中有侵权行为,请与本站客服联系(QQ:99698058)!
上一节 下一节
相关教程  
其他教程  
站长软文  
PHP基础
PHP技巧
PHP实例
PHP文摘
PHP模板
PHP总结

Copyright©威凡软文网 版权所有 宁网通旗下网站 苏ICP备18030957号
站长QQ:99698058 电话:18013800932