Pinging a website with PHP.

Pinging a website in PHP is pretty easy if you know how to use the function fsockopen.

For this example, we’ve created a custom PHP function called ping, which carries out the bulk of the work.

function ping($host){
    $start = microtime(true);
    $fp = fsockopen($host, 80, $errorCode, $errorCode, 5);
    $end = microtime(true);
    if($fp === false){
        return false;
    }
    fclose($fp);
    $diff = $end - $start;
    return sprintf('%.16f', $diff);
}

A simple explanation of the code above.

  1. Firstly, we start the timer by using PHP’s microtime function. We pass in a boolean TRUE parameter because we want the return value to be a float. This is important as we will be carrying out some basic arithmetic on it.
  2. We then attempt to connect to the given host via port 80. We are using port 80 because we are pinging a website and that is the default port number for HTTP. For mail servers and the like, you will need to specify a different port number (for SMTP, it will probably be port 25). If the site uses HTTPS, then you can use 443.
  3. We get the “end” microtime.
  4. If $fp is a boolean FALSE value, then it means that we were unable to connect to the site. In this scenario, our custom function returns a FALSE value.
  5. We close the file pointer using fclose.
  6. We calculate the amount of time that it took to perform the request.
  7. Finally, we return a formatted string that contains the time that it took to ping the website in question.