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:
- 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 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).
- We get the “end” microtime.
- If $fp is a boolean FALSE value, it means that we were unable to connect. In this scenario, we return a FALSE value.
- We close the file pointer using fclose.
- We calculate the amount of time that it took to perform the request.
- We return a formatted string that contains the time that it took to ping the website in question.
0 comments:
Post a Comment