jump to navigation

fsockopen()to check your server status – a basic ping with PHP October 15, 2010

Posted by Tournas Dimitrios in PHP.
trackback

In this tutorial I will show you how to check whether a domain, server is up or down and how fast it is. Generally speaking we will implement a ping command with PHP.
PHP has no built in function for the ping functionality so we need to find a way how to realize it. We want to know two information about the given domain. First of all we want to know whether it is available or not and as second it would be nice to get information about how fast the response is.
The main concept is that we try to connect to the server with socket connection on port 80 and measure the time how long does it take. To do this we will use the built in PHP function fsockopen() which opens Internet or Unix domain socket connection. On depends the return value we can decide whether the actual domain is available at the moment or not.
First we will implement the main function which will get a domain name as parameter and try to open it. The function will returns with the response time if the connection was success and -1 in other case. The function makes no input validation so it must be done before calling it. I will show it later.
Let’s see the main steps:

  • Save current time as startTime
  • Try to connect to the domain
  • Save current time again as stopTime
  • Check the return value
    • In case of error return with -1
    • In case of successfully connection calculate the time in ms and return with it.

The code looks like this:

<?php
// Function to check response time
function pingDomain($domain){
    $starttime = microtime(true);
    $file      = fsockopen ($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file) $status = -1;  // Site is down
    else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}
?>

Now let’s create some usable environment for our function. It means that we will create a HTML form where the visitor can define the domain name in a normal text field. As action parameter we will call our script again. I do’nt use  any special formatting and CSS to make this example as simple as it can be and focus only on the main topic.
The resulted form is quite simple:

"&nbsp;method="post" name="domain">
 Domain&nbsp;name:
 <table>
 <input&nbsp;name="domainname" type="text"&nbsp;>
 <input&nbsp;type="submit" name="submitBtn" value="Ping domain">
 </table>
 </form>

During the form processing we need to validate the domain name. In this case it means that to be sure we remove the http:// prefix if it was submitted with the domain name. Here you can add more validation routines if you want. Now we can call the above implemented function with the given domain and display the result depending on the return value.

<? php
    // Check whether the for was submitted
    if (isset($_POST['submitBtn'])){
        $domainbase = (isset($_POST['domainname'])) ? $_POST['domainname'] : '';
        $domainbase = str_replace("http://","",strtolower($domainbase));

        echo '<table>';

        $status = pingDomain($domainbase);
        if ($status != -1) echo "http://$domainbase is ALIVE ($status ms)";
        else  echo "http://$domainbase is DOWN";

         echo '</table>';
    }
?> 

And we are all done.

The complete code looks like this:

<?php
// Function to check response time
function pingDomain($domain){
    $starttime = microtime(true);
    $file      = fsockopen ($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file) $status = -1;  // Site is down
    else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}
?>

<DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="domain">
        Domain name:
        <table>
          <input name="domainname" type="text" >
          <input type="submit" name="submitBtn" value="Ping domain">
        </table>
      </form>
<?php
    // Check whether the for was submitted
    if (isset($_POST['submitBtn'])){
        $domainbase = (isset($_POST['domainname'])) ? $_POST['domainname'] : '';
        $domainbase = str_replace("http://","",strtolower($domainbase));

        echo '<table>';

        $status = pingDomain($domainbase);
        if ($status != -1) echo "<tr><td>http://$domainbase is ALIVE ($status ms)</td><tr>";
        else  echo "<tr><td>http://$domainbase is DOWN</td><tr>";

         echo '</table>';
    }
?>
</body>
</html>
Update 18/07/2012 :
Using PEAR’s HTTP-Modul :

PEAR’s HTTP_Request2 package provides an easy way for PHP applications to perform HTTP requests  . It’s default built-in stream_socket_client() function , does not require any special extensions or configuration . Note that this is a pure PHP implementation of HTTP protocol , it does not use http stream wrapper .Whatever  Adapter is used for sending the request , a remote server’s response can be parsed ( response-Code or  Content ) . The following code demonstrates this functionality .

<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2('https://tournasdimitrios1.wordpress.com', HTTP_Request2::METHOD_GET);
try {
    $response = $request->send();	
    if (200 == $response->getStatus()) {
  //echo $response->getBody();//Get content of page
var_dump($response->getStatus());
    } else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .$response->getReasonPhrase();
    }
} catch (HTTP_Request2_Exception $e) {
    echo 'Error: ' . $e->getMessage();
}
?>

Comments»

1. Chris - January 11, 2011

Is there anyway to check if an email address is active with a similar function in this tutorial? Thanks in advance

tournasdimitrios1 - January 11, 2011

@Chris
Hi ,
You can’t really ping an email address, the best you can really do is, which I’m sure you’ve seen, send a message and have the person click on a link in the email which goes to your site and confirms the address.That’s the way most e-commerce websites verify the email address .
If you could it would be a field day for spammers, they could just send that request to every mailserver in the world for every possible combination of characters and get a list of known-good addresses back.
Just for sake of completeness, you *could* verify the existence of email addresses using the VRFY and EXPN commands of the SMTP protocol (see RFC 2821).
Unfortunately, thanks to spammers, these commands are ignored or return an error on most servers, despite the fact that they would be quite useful in practice.
This forum has a totally different statement >>>>>

2. MarkL - March 25, 2011

It’s be great if you could also check if SSL is enabled or not.

tournasdimitrios1 - March 25, 2011

@MarkL
The concepts remain the same , even on SSL (https://) .
Just the communication is done on port 443 . SSL encrypts the actual data not the headers of the packet .Tcpdump is a nice Linux command line utility to discover the packet structure , an Gui alternative is Wireshark

MarkL - March 25, 2011

it’s possible to specify “ssl://” as well.

tournasdimitrios1 - March 25, 2011

@MarkL
According to this guide .
HTTP is an application layer network protocol built on top of TCP, operates at OSI Layer 7 (Application)
SSL is a standard for encrypted client/server communication between network devices. A network protocol, SSL runs on top of TCP/IP and operates at OSI layer 6 (presentation).
Although browsers behind the scenes can handel lower level (OSI) functionality , it’s API works on layer 7 of the OSI model .
Try to access this website : https://secure.wikimedia.org/wikipedia/en/wiki/Main_Page
you can’t use ssl://secure.wikimedia.org/wikipedia/en/wiki/Main_Page
Of course socket communications are another story , that’s what browsers are handle behind the scenes .

3. Fair - August 7, 2012

You can certainly see your skills within the work you write. The arena hopes for more passionate writers such as you who aren’t afraid to mention how they believe. Always go after your heart.

4. Disable Dangerous Functions in PHP « Tournas Dimitrios - November 30, 2012

[…] a little bit of code the same functionality can be done with PHP’s build-in functionality (fsockopen function) .  Which commands should you use and when ? This is entirely up to you and the needs you have […]

5. allie - May 18, 2013

Good blog you’ve got here.. It’s difficult to find high-quality writing like yours these days.
I really appreciate individuals like you! Take care!!

6. lordzurp - July 3, 2014

Thanks you for your small but usefull code bro 🙂


Leave a comment