How to check your server status using PHP

For a website administrator it is very important to determine the status of his web server on a regular basis. Here, I will show you how to check the status of a given web server by using PHP. In order to check the server status we will ping it. Also, we will calculate the time taken by the server to respond. This will give us an idea as to how fast is our server. So let's get started.

To ping to the server we use fsockopen() function. We jot down the time before and after making the ping by using microtime() function. This enables us to determine the overall time taken by the server to respond to our ping.

Create a new PHP file named server_status.php and add the following code to it:

<?php function check_server_status($host, $port, $timeout) { $start_time = microtime(TRUE); $status = fsockopen($host, $port, $errno, $errstr, $timeout); if (!$status) { return "Server is down."; } $end_time = microtime(TRUE); $time_taken = $end_time - $start_time; $time_taken = round($time_taken,5); return "Server responded in " . $time_taken * 1000 . " ms."; } ?> <form action="" method="post"> Domain name: <input type="text" name="domain" value="www.botskool.com" /> <input type="submit" value="Submit" /> </form> <strong> <?php if($_POST['domain']) echo "Status: " . check_server_status($_POST['domain'], 80, 12); ?> </strong>

The working demonstration of the above code is shown below:

Here, we have defined a function named check_server_status(). It initiates a connection to the desired domain and also calculates the time taken to respond by the server in milliseconds. Finally, the function returns this value.

We use a form to obtain the value of the domain name for which the status is to be checked. On submission of the form the status is checked and reported. That's it! GSUDXE56VJJE