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.
- 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.
- 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.
- We get the “end” microtime.
- 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.
- We close the file pointer using fclose.
- We calculate the amount of time that it took to perform the request.
- Finally, we return a formatted string that contains the time that it took to ping the website in question.