PHP ping script examples

While working on a shared hosting server, I found that the company I'm working with has disabled my access to the Unix/Linux ping command. Not to be deterred, I found several different ways to run a ping command with a PHP script.

Use the Net_Ping module

The first thing you can try to do is use the PHP PEAR Net_Ping module to get around this problem. In short, you install it like this:

pear install Net_Ping

Then use it like this:

<?php
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping)) {
  echo $ping->getMessage();
} else {
  $ping->setArgs(array('count' => 2));
  var_dump($ping->ping('example.com'));
}
?>

This is shown at the documentation page for this module.

This didn't work for me, as they also disabled access to the PHP pear command.

Use the PHP Curl module

The next thing I tried (and what worked for me) is to use a PHP Curl script I found that emulates a little bit of what the ping command does. It's important to note that this isn't technically true: The ping command uses a totally different protocol than the approach shown here, but for my purposes I just needed to see if a remote web server was alive, so it didn't really matter to me whether I used ping or a curl command like this.

Here's a modified version of the original source code:

<?php

$url = 'www.google.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
  echo 'worked';
} else {
  echo "didn't work";
}

?>

You can find the original source code at this "Lost in Code" URL.

Issue a ping command from a PHP script

As a final option, if you can run the ping command from your command line, you can also just execute it with a PHP ping script, like this:

<?php
$str = exec("ping -c 1 www.google.com");
if ($result == 0){
  echo "ping succeeded";
}else{
  echo "ping failed";
}
?>

In my case this didn't work because I wasn't given access to the ping command, but if you do have access to the ping command at the command line, this "PHP exec" example shows how this can work.

PHP ping script examples

I hope these PHP ping script examples have been helpful. If you have any other approaches you'd like to share (using a PHP socket, for instance), or questions about these, just leave a comment below.