Home >Backend Development >PHP Problem >How to implement ping in php
##The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computerHow to implement the ping function in php: 1. Open the exec function in php.ini; 2. Create a PHP sample file; 3. Implement it through the "function ping_time($ip) {...}" method Just use the ping function.
phpHow to implement ping?
php implements the ping function
The code is as follows:<?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));Pay attention to enable the exec function in php.ini. Recommended learning: "
PHP Video Tutorial"
The above is the detailed content of How to implement ping in php. For more information, please follow other related articles on the PHP Chinese website!