Tuesday, February 12, 2019

How to ping an IP address from PHP script?

<?php

$ip_address =   "32.33.45.67"; //ip or web address
exec("ping -n 3 $ip_address", $output, $status);
print_r($output);

?>

The above script will try to ping the IP address 3 times and the response will be available in variable output. It is an array variable and result will look like below

Array
(
    [0] =>
    [1] => Pinging 32.33.45.67 with 32 bytes of data:
    [2] => Reply from 32.33.45.67: bytes=32 time<1ms TTL=128
    [3] => Reply from 32.33.45.67: bytes=32 time<1ms TTL=128
    [4] => Reply from 32.33.45.67: bytes=32 time<1ms TTL=128
    [5] =>
    [6] => Ping statistics for 32.33.45.67:
    [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
)

If you are running the above script from Linux and the output array results empty, then try

exec("ping -c 3 $ip_address", $output, $status);

You can also check the value of $status for the ping status. It will result in 0 if ping is successful.

No comments:

Post a Comment