Ping a server using PHP
Posted in php | Posted on 13-09-2008
PEAR’s Net_Ping is a niffty wrapper class for executing ping calls from PHP. You can use it to check if a remote server is responding correctly. The library can be download fromĀ here. A example is given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php require_once "Net/Ping.php"; $ping = Net_Ping::factory(); if(PEAR::isError($ping)) echo $ping->getMessage(); else { /* Number of packets to send */ $ping->setArgs(array('count' => 4)); $rawData = $ping->ping('google.com'); print_r($rawData); } ?> |
The output of the same is shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | Net_Ping_Result Object ( [_icmp_sequence] => Array ( [1] => 310 [2] => 300 [3] => 318 [4] => 301 ) [_target_ip] => 64.233.167.99 [_bytes_per_request] => 32 [_bytes_total] => 128 [_ttl] => 238 [_raw_data] => Array ( [0] => [1] => Pinging google.com [64.233.167.99] with 32 bytes of data: [2] => [3] => Reply from 64.233.167.99: bytes=32 time=310ms TTL=238 [4] => Reply from 64.233.167.99: bytes=32 time=300ms TTL=238 [5] => Reply from 64.233.167.99: bytes=32 time=318ms TTL=238 [6] => Reply from 64.233.167.99: bytes=32 time=301ms TTL=238 [7] => [8] => Ping statistics for 64.233.167.99: [9] => Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), [10] => Approximate round trip times in milli-seconds: [11] => Minimum = 300ms, Maximum = 318ms, Average = 307ms ) [_sysname] => windows [_round_trip] => Array ( [min] => 300 [max] => 318 [avg] => 307 ) [_transmitted] => 4 [_received] => 4 [_loss] => 0 ) |

Hello,
I have found your post about pinging in php with the pear net_ping class.
Could you please tell me how I can use the output data? I have no clue how to use the data so I echo for example the IP adres on a page.
By thanking you in advance,
To get the IP element for example use the following:
$ip = $rawData->_target_ip;
and so on.
Now if you want tot get the ‘_raw_data’ element, you will see that it is an array, so we will have to loop through the same, like this:
foreach($rawData->_raw_data as $data)
echo $data . “\n”;
can any one help me out how to print down the value of the array..?
A easy way is to run the code from the command line and redirect the output to a text file, which you can print as shown below. Assuming your code filename is Ping.php.
c:\php Ping.php > pingdata.txt