本文操作环境:windows7系统、PHP7.1版、DELL G3电脑
php怎么实现ping?
php实现ping功能
代码如下:
<?php
function ping_time($ip) {
$ping_cmd = "ping -c 1 -w 5 " . $ip;
exec($ping_cmd, $info);
if($info == null)
{
return json_encode(['code'=>404,'msg'=>"Ping请求找不到主机".$ip.";请检查该名称,然后重试"]);die;
}
//判断是否丢包
$str1 = $info['4'];
$str2 = "1 packets transmitted, 1 received, 0% packet loss";
if( strpos( $str1 , $str2 ) === false)
{
return json_encode(['code'=>403,'msg'=>"当前网络堵塞,请求无法成功,请稍后重试"]);die;
}
$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['domain_ip'] = $info['0'];
$result['ping_min'] = $ping_time_min;
$result['ping_avg'] = $ping_time_avg;
$result['ping_max'] = $ping_time_max;
return json_encode(['code'=>200,'msg'=>"请求成功",'data'=>$result]);
}
$ip = $_POST['ip'];
print_r(ping_time($ip));
注意去php.ini中开通exec函数。