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, I’ve created a custom PHP function called ping, which basically carries out the bulk of the work:

A simple explanation of the code above:

  1. 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 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).
  3. We get the “end” microtime.
  4. If $fp is a boolean FALSE value, it means that we were unable to connect. In this scenario, we return 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. We return a formatted string that contains the time that it took to ping the website in question.

Comments

comments