Home  >  Article  >  Backend Development  >  How to implement ping in php

How to implement ping in php

藏色散人
藏色散人Original
2021-10-15 10:11:164798browse

How 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.

How to implement ping in php

##The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

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([&#39;code&#39;=>404,&#39;msg&#39;=>"Ping请求找不到主机".$ip.";请检查该名称,然后重试"]);die;
  }
  //判断是否丢包
  $str1 = $info[&#39;4&#39;];
  $str2 = "1 packets transmitted, 1 received, 0% packet loss";
  if( strpos( $str1 , $str2 ) === false)
  {
     return json_encode([&#39;code&#39;=>403,&#39;msg&#39;=>"当前网络堵塞,请求无法成功,请稍后重试"]);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[&#39;domain_ip&#39;] = $info[&#39;0&#39;];
  $result[&#39;ping_min&#39;] = $ping_time_min;
  $result[&#39;ping_avg&#39;] = $ping_time_avg;
  $result[&#39;ping_max&#39;] = $ping_time_max;
    
  return json_encode([&#39;code&#39;=>200,&#39;msg&#39;=>"请求成功",&#39;data&#39;=>$result]);
}
  
$ip = $_POST[&#39;ip&#39;];  
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn