Hướng dẫn dùng ping -f trong PHP

Có thể trùng lặp:
Ping một địa chỉ IP bằng PHP và lặp lại kết quả

Làm thế nào để bạn ping một địa chỉ ip trong php. và đưa ra kết quả như thể bạn đang sử dụng chương trình cmd trong windows



   echo “pinged”;
?>
  • php
  • ip-address
  • ping

17 hữu ích 1 bình luận 90k xem chia sẻ

answer

20

Hướng dẫn dùng ping -f trong PHP

$ip =   "127.0.0.1";
exec("ping -n 3 $ip", $output, $status);
print_r($output);

đầu ra trông giống như bên dưới

Array
(
    [0] => 
    [1] => Pinging 127.0.0.1 with 32 bytes of data:
    [2] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    [3] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    [4] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    [5] => 
    [6] => Ping statistics for 127.0.0.1:
    [7] =>     Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
    [8] => Approximate round trip times in milli-seconds:
    [9] =>     Minimum = 0ms, Maximum = 0ms, Average = 0ms
)

20 hữu ích 5 bình luận chia sẻ

answer

21

Thử cái này

$host="192.168.0.104";

exec("ping -c 4 " . $host, $output, $result);

print_r($output);

if ($result == 0)

echo "Ping successful!";

else

echo "Ping unsuccessful!";

Lưu ý: Điều này phụ thuộc vào hệ điều hành bạn đang chạy. Windows sẽ mặc định chỉ có 4 ping trong khi Linux sẽ ping mãi mãi.

Để ping hai lần trong Windows, hãy sử dụng "ping -n 2 host"

Để ping hai lần trong Linux, hãy sử dụng "ping -c 2 host"

21 hữu ích 0 bình luận chia sẻ

answer

2

Tôi vừa ping google với giám đốc điều hành đó


đầu ra là:

Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

2 hữu ích 0 bình luận chia sẻ

Đăng nhập để trả lời câu hỏi

Có thể bạn quan tâm

Bài viết hướng dẫn cách thực thi dòng lệnh trên server bằng PHP nhưng hiển thị realtime đầu ra trên trình duyệt.

Có nhiều hàm thực thi dòng lệnh, tôi thường dùng hàm proc_open() để có thể kiểm soát được cả STDIN, STDOUTSTDERR.

Hiển thị realtime không cần xử lý gì ở client

Để hiển thị realtime trên trình duyệt mà không cần xử lý gì ở client thì phía server phải đảm bảo 2 vấn đề:

  • Tắt output buffer để mỗi khi lệnh có output thì hiện ra kịp thời chứ không bị tích lại trong output buffer.
  • Content Type phải là text/html.

Ví dụ sau hiển thị đầu ra của lệnh PING trên màn hình trình duyệt.

ping-test.php

 1000, // 1000 packets
  '-a', // resolve IP address to hostname
  '8.8.8.8', // Target IP address
);

/// Form the command line
$cmd = escapeshellarg($cmd);
foreach ($args as $arg => $value) :
  if (is_string($arg)) :
    $cmd .= ' ' . escapeshellarg($arg) . ' ' . escapeshellarg($value);
  else :
    $cmd .= ' ' . escapeshellarg($value);
  endif;
endforeach;

$descriptorspec = array(
  0 => array("pipe", "r"), // stdin
  1 => array("pipe", "w"), // stdout
  2 => array("pipe", "w")  // stderr
);
$cwd = NULL;
$env = NULL;
$options = array('bypass_shell' => true);

disable_ob();

$process = proc_open($cmd, $descriptorspec, $pipes, $cwd, $env, $options);

if ( is_resource($process) ) :
  header("Content-type: text/html; charset=utf-8"); 
  echo "
";

  while ($s = fgets($pipes[1])) {
    print htmlspecialchars( $s );
    flush(); // dump the line immediately
  }
  $retval = proc_close($process);
  echo "\nCommand returned $retval\n";

  echo "
"; endif; /** * Turn off Output Buffer. */ function disable_ob() { // Turn off output buffering ini_set('output_buffering', 'off'); // Turn off PHP output compression ini_set('zlib.output_compression', false); // Implicitly flush the buffer(s) ini_set('implicit_flush', true); ob_implicit_flush(true); // Clear, and turn off output buffering while (ob_get_level() > 0) { // Get the curent level $level = ob_get_level(); // End the buffering ob_end_clean(); // If the current level has not changed, abort if (ob_get_level() == $level) break; } // Disable apache output buffering/compression if (function_exists('apache_setenv')) { apache_setenv('no-gzip', '1'); apache_setenv('dont-vary', '1'); } } ?>

Nếu chú ý bạn sẽ thấy các thẻ đóng (điển hình là của , và thẻ chứa đầu ra của lệnh ở đây là

) sẽ không được ghi ra cho đến khi lệnh thực hiện xong.

Đặc biệt nếu HTML có chứa CSS và JavaScript sẽ khó có thể thực thi chính xác khi DOM còn chưa sẵn sàng.

Vì vậy giải pháp tốt hơn là hãy sử dụng Server-sent Events để phía client xử lý đầu ra của lệnh một cách chủ động khi mọi thứ đã sẵn sàng.

Hiển thị realtime dùng Server-sent Events

Ta chỉnh lại đoạn mã trên một chút:

  • Đổi content type thành text/event-stream.
  • Ghi chuỗi đầu ra theo format của event stream. Xem thêm ›.

ping-test-sse.php

 1000, // 1000 packets
  '-a', // resolve IP address to hostname
  '8.8.8.8', // Target IP address
);

/// Form the command line
$cmd = escapeshellarg($cmd);
foreach ($args as $arg => $value) :
  if (is_string($arg)) :
    $cmd .= ' ' . escapeshellarg($arg) . ' ' . escapeshellarg($value);
  else :
    $cmd .= ' ' . escapeshellarg($value);
  endif;
endforeach;

$descriptorspec = array(
  0 => array("pipe", "r"), // stdin
  1 => array("pipe", "w"), // stdout
  2 => array("pipe", "w")  // stderr
);
$cwd = NULL;
$env = NULL;
$options = array('bypass_shell' => true);

disable_ob();

$process = proc_open($cmd, $descriptorspec, $pipes, $cwd, $env, $options);

if ( is_resource($process) ) :
  header("Content-type: text/event-stream; charset=utf-8"); 

  while ($s = fgets($pipes[1])) :
    print "data: " . htmlspecialchars( $s ) . PHP_EOL;
    print PHP_EOL;
    flush(); // dump the line immediately
  endwhile;
  $retval = proc_close($process);

  print "id: close" . PHP_EOL; // notify end of script

  print "data: Command returned $retval" . PHP_EOL;
  print PHP_EOL;
endif;

/**
 * Turn off Output Buffer.
 */
function disable_ob() {
  // Turn off output buffering
  ini_set('output_buffering', 'off');

  // Turn off PHP output compression
  ini_set('zlib.output_compression', false);

  // Implicitly flush the buffer(s)
  ini_set('implicit_flush', true);
  ob_implicit_flush(true);

  // Clear, and turn off output buffering
  while (ob_get_level() > 0) {
    // Get the curent level
    $level = ob_get_level();

    // End the buffering
    ob_end_clean();

    // If the current level has not changed, abort
    if (ob_get_level() == $level) break;
  }

  // Disable apache output buffering/compression
  if (function_exists('apache_setenv')) {
    apache_setenv('no-gzip', '1');
    apache_setenv('dont-vary', '1');
  }
}
?>

Trong đó phần được thay đổi là

header("Content-type: text/event-stream; charset=utf-8"); 

while ($s = fgets($pipes[1])) {
  print "data: " . $s . PHP_EOL;
  print PHP_EOL;
  flush(); // dump the line immediately
}
$retval = proc_close($process);

print "id: close" . PHP_EOL; // notify end of script

print "data: Command returned $retval" . PHP_EOL;
print PHP_EOL;

Phía client chuẩn bị một nội dung HTML như sau:





Ping SSE






Đoạn mã JavaScript dùng EventSource để đọc đầu ra của lệnh, chèn vào giữa

 mỗi khi có data mới.

sse.js

if ( !!window.EventSource ) {
  var output = document.getElementById("output");
  var source = new EventSource("ping-test-sse.php");

  source.onopen = function(e) {
    console.log("SSE connection was established");
  };

  source.onerror = function(e) {
    alert("SSE error!");
    console.error(e);
  }

  source.onmessage = function(e) {
    output.innerHTML += e.data + "\r\n";

    if (e.lastEventId === 'close') // id 'close' was found
      source.close();
  };
} else {
  alert("Your web browser does not support SSE");
}

Như vậy với cách làm này, thì phần CSS và JavaScript xử lý đã được load đầy đủ khi thực thi lệnh, giao diện hiển thị kết quả sẽ được đảm bảo.