Using PHP to check response time of HTTP-server

I must start off with admiting that my PHP skills are very limited, however being a very experienced Perl hacker this is very similar to me. Edit 2013-01-30: This is no longer true 🙂

I needed a script that checked for a normal HTTP response from another server, a status script to see if the other server(s) where behaving as they should.

The resources on-line for PHP are great and I quickly found the code needed to retrieve a remote page and read the contents. I also found some tutorials describing how to use this code. My version ended up looking like this (thanks phptoys.com for the tutorial!):

<?php
// check responsetime for a webbserver
function pingDomain($domain){
    $starttime = microtime(true);
    // supress error messages with @
    $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;
}
?>

What this code does is to measure, using the microtime function, the time difference between initiating a connection using fsockopen and when that functions has completed executing. If a connection was established the time difference is returned. If fsockopen failed to open a connection -1 is returned.

The time difference is multiplied by 1000 to get the number of milliseconds it took, floor() is then used to round down to the nearest integer value.

To call this function simply add the domain or IP you want to check the response time of:

Fireflake: <?php echo pingDomain('tech.fireflake.com'); ?> ms<br>
Example: <?php echo pingDomain('www.example.com'); ?> ms<br>
Internal IP: <?php echo pingDomain('192.168.0.2'); ?> ms<br>
Fail: <?php echo pingDomain('fail.fireflake.com'); ?> ms<br>

Sample output from the above statements are:

Fireflake: 111 ms
Example: 139 ms
Internal IP: 0 ms
Fail: -1 ms

Also, sometimes DNS servers return a “search engine” response if the domain is unknown or unreachable. To be sure you reach the server you want try calling it by IP-number instead to make sure your DNS isn’t fooling you.

EDIT:  Thx for adding the tip to use @ to supress error messages. Just use @fsockopen to supress the inevitable error message.

EDIT 2013-01-30: Fixed the old code and added some more examples.

EDIT 2013-03-07: Added clarification about unit used in $status.