PHP Internet Services Checking If a Host Is Alive - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Internet Services Checking If a Host Is Alive - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Saturday, June 22, 2019

PHP Internet Services Checking If a Host Is Alive

PHP Internet Services


Checking If a Host Is Alive

Problem

You want to ping a host to see if it is still up and accessible from your location.

Solution

Use PEAR’s Net_Ping package:

       require 'Net/Ping.php';

       $ping = Net_Ping::factory();
       if ($ping->checkHost('www.oreilly.com')) {
              print 'Reachable';
       } else {
              print 'Unreachable';
       }

       $data = $ping->ping('www.oreilly.com');

Discussion

The ping program tries to send a message from your machine to another. If everything goes well, you get a series of statistics chronicling the transaction. An error means that ping can’t reach the host for some reason.

On error, Net_Ping::checkhost() returns false, and Net_Ping::ping() returns the constant PING_HOST_NOT_FOUND. If there’s a problem running the ping program (because Net_Ping is really just a wrapper for the program), PING_FAILED is returned.

If everything is okay, you receive a Net_Ping_Result object. This object has assorted methods allowing you to retrieve the information about the ping operation. For example:

       require 'Net/Ping.php';
       $ping = Net_Ping::factory();

       $result = $ping->ping('www.oreilly.com');
       print<<<_INFO_
       Ping of www.oreilly.com ({$result->getTargetIp()})
       with {$result->getTransmitted()} requests had
       a minimum time of {$result->getMin()} ms and
       a maximum time of {$result->getMax()} ms.
       _INFO_
       ;

This prints something like:

       Ping of www.oreilly.com (23.67.61.152)
       with 3 requests had
       a minimum time of 35.4 ms and
       a maximum time of 40.586 ms.

The Net_Ping::setArgs() method lets you change a few things about how the ping program is run. For example, you can call $ping->setArgs(array('count' => 7)) to tell Net_Ping to send seven ping packets instead of the default (usually three or four).


No comments:

Post a Comment

Post Top Ad