If you're building a distributed PHP-based Web application, there may come a time when you'll need to ping a remote host. Maybe it's just to see if the host is alive before redirecting a browser, or to see if a remote service is up and running. The PHP Extension and Application Repository (PEAR) has a handy Net/* hierarchy that makes it a cinch, specifically the Net_Ping class.
The Net_Ping class, maintained by Marten Jansen, is available as a free download from the PEAR Web site. As its name implies, this class lets you "ping" a host with multiple data packets and evaluate the response to see if it's alive or not.
Here's a simple example of how to use this class:<?php
// include class
// create object
$ping = Net_Ping::factory();
// ping host and display response
$response = $ping->ping('w3c.org');
It's pretty straightforward—create an instance of the Net_Ping class, pass the domain name to the ping() method, and read the result. The ping() method executes the operating system's ping program and returns an associative array containing the raw data and packet statistics. Listing A has an example of what this array looks like.
Most of us would probably prefer that output be massaged into a format suitable for user viewing. Thankfully, Net_Ping doesn't end with the simple ping method—it provides a number of functions for retrieving ping statistics.