PHP Ping Script To Check Remote Server Or Website

Overview

Ever needed a quick php code snippet to perform a ping to check if a remote server or website is up? Then see the code below which contains two variations of a ping function that will show you how to ping from php using a PHP Ping Script. The first version uses exec() and the second version uses fsockopen().

PHP Ping Website

The advantage of the second function is that it can connect to a specified port which allows you to also check if a port or service is available on your server. Great if you want to check if your Website is still running on port 80 or if your MySQL service is still responding.

PHP Ping Script To Check Remote Server Or Website

A PHP Ping Script can be very useful to check if your website or server is up before attempting to connect to it resulting in you having to wait for ages while the program or script to eventually timeout.

Our first version using PHP exec() to ping the server.

First example is a simple example that will send a standard ping.

<?php

/* our simple php ping function */
function ping($host)
{
	exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($host)), $res, $rval);
	return $rval === 0;
}

/* check if the host is up
	$host can also be an ip address */
$host = 'www.example.com';
$up = ping($host);

/* optionally display either a red or green image to signify the server status */
echo '<img src="'.($up ? 'on' : 'off').'.jpg" alt="'.($up ? 'up' : 'down').'" />';

?>

Our alternate PHP Ping Script using fsockopen().

Our second example is by far more useful as it accepts a port as the parameter. This allows us to check specific services on the server. Using port 80 in most cases will test the website, or 3306 will try connect to a mysql server.

<?php

function ping($host,$port=80,$timeout=6)
{
	$fsock = fsockopen($host, $port, $errno, $errstr, $timeout);
	if ( ! $fsock )
	{
		return FALSE;
	}
	else
	{
		return TRUE;
	}
}

?>

Useful Example of Using PHP Ping Script

We can use this ping function to allow us to provide our users with a better message rather than seeing our site is down.

<?php

$host = 'www.example.com';
$up = ping($host);

// if site is up, send them to the site.
if( $up ) {
	header('Location: http://'.$host);
}
// otherwise, take them to another one of our sites and show them a descriptive message
else {
	header('Location: http://www.anothersite.com/some_message');
}

?>

Now if the site is up, they will get sent to your site. Otherwise they will be sent to www.anothersite.com and shown a message.