Pinging a remote host in PHP
Takeaway: The PHP Extension and Application Repository (PEAR) has a handy Net_Ping class that makes it a cinch to run a ping from your PHP application. Here are the basics on how to use Net_Ping.
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
require ("Net/Ping.php");
// create object
$ping = Net_Ping::factory();
// ping host and display response
if(!PEAR::isError($ping))
{
$response = $ping->ping('w3c.org');
print_r($response);
}
?>
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.
More PHP network functions
There are other useful classes in the hierarchy besides Net_Ping(), including support for traceroute and DNS functions.
Print/View all Posts Comments on this article
SponsoredWhite Papers, Webcasts, and Downloads
- Protect your company's admin-level identities Quest Software
- Riverbed Raises the Ante Again in WDS with RiOS 5.0 Riverbed
- Live Webcast: Energy Efficient Data Centers - Lower Costs, Greener Outcomes PC Connection
- CRM Your Salespeople Will Love Oracle
- The Road Ahead for Business Process Management SAP
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET
