Showing Uptime of Server Status on Webpages using PHP and Crontab


We all know, previously, in this post, that we can use shell_exec or exec in PHP to get the output of an external program on the server. So obviously, we can run linux command uptime to get the status of the server, which gives something like this (or if you scroll down this blog, at the end of this page, you will find almost real time status update, i.e. updated every 5 minutes):

1
 10:25:01 up 31 days, 15:17,  0 users,  load average: 0.01, 0.09, 0.12
 10:25:01 up 31 days, 15:17,  0 users,  load average: 0.01, 0.09, 0.12

However, it is not recommended to invoke directly the uptime command using shell_exec or exec
because of these reasons. First, shell_exec and exec may be disabled (as far as I know) by web hosting companies, mainly on the shared hosts for security purposes. Fasthosts disables this but Godday, on the other hand, does not forbid this usage. Second, it is considered inefficient and time (CPU) consuming to run these two commands at real time within PHP scripts.

The correct/recommended way to obtain such information is as follows: First, create a crontab that runs at a time interval, e.g. every 2 minutes on the server, using crontab -e will allow you to edit the jobs using your favourite text editor such as nano or vim.

1
*/2 * * * * /usr/bin/uptime > $HOME/htdocs/uptime.txt
*/2 * * * * /usr/bin/uptime > $HOME/htdocs/uptime.txt

Thus, every 2 minute (remove /2 for every minute), the file uptime.txt will be updated and put under the public HTTP folder. So you can using following PHP script to obtain such data.

1
2
3
4
$uptime = file_get_contents('http://'.$_SERVER['SERVER_NAME'].'/uptime.txt');
if ($uptime) {
  echo $uptime;
}
$uptime = file_get_contents('http://'.$_SERVER['SERVER_NAME'].'/uptime.txt');
if ($uptime) {
  echo $uptime;
}

Sounds pretty easy, right? This gives you a relatively accurate uptime status and you could put this information at the footer.php of wordpress blog (scroll down to the end of page for example).

You might also use DOCUMENT_ROOT server variable which represents the root directory of a website. So, make sure the uptime.txt is located at the root directory of a website.

1
2
3
4
5
$uptime = '';
$uptimefile = $_SERVER['DOCUMENT_ROOT'] . '/uptime.txt';
if (is_file($uptimefile)) {
    $uptime = @file_get_contents($uptimefile);
}  
$uptime = '';
$uptimefile = $_SERVER['DOCUMENT_ROOT'] . '/uptime.txt';
if (is_file($uptimefile)) {
    $uptime = @file_get_contents($uptimefile);
}  

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
472 words
Last Post: Left and Right Function in PHP
Next Post: Common Javascript Functions for Financial Calculations

The Permanent URL is: Showing Uptime of Server Status on Webpages using PHP and Crontab

Leave a Reply