Retrieving ping statistics with PEAR's Net_Ping

The PHP Extension and Application Repository (PEAR) has a Net_Ping class that lets you run a ping from PHP. It also includes methods for converting the response data into a readable format.

The PHP Extension and Application Repository (PEAR) has a Net/* hierarchy that includes a number of classes for interacting with the network layer. One particularly handy class is Net_Ping, which, as the name implies, lets you run a ping from PHP.

You use the ping() method to run a basic network ping. That method returns an associative array containing the raw data and packet statistics (Listing A).

Readable ping data

Most of us would probably prefer the output in a more readable format. To this end, the Net_Ping class offers a number of methods designed to extract specific subsets of data from the array in Listing A. These include getTargetIp() for the IP address; getMin(), getMax(), and getAvg() for response times; getLoss() for the number of lost packets; getBytesTotal() for the total number of bytes transmitted; and getRawData() for the raw output of the ping command.

Consider the example in Listing B, which demonstrates these methods (and a few others) in action. There are three items of note in this example code:

1. We've revised the script from our basic ping example to make it more interactive. The domain name can now be retrieved from the user through a form instead of being hardwired into the script.

2. The response returned by the remote host is broken down using the methods listed previously and is formatted into a neat report. Look in the script comments to see exactly what each method does, or run the ping command at your shell prompt to gain a better understanding of what each field means.

3. The setArgs() method is used to pass additional parameters to the ping command. This method accepts an associative array of variable-value pairs. The two important ones here are "size", which controls the size, in bytes, of the ping packets transmitted, and "count", which controls the total number of packets transmitted. The script above allows the user to specify the latter variable through a form field.

More PHP network functions

There are other useful classes in the Net/* hierarchy besides Net_Ping, including support for traceroute and DNS functions.

Editor's Picks

Free Newsletters, In your Inbox