Calculating Sever Uptime in PHP

This little bit of simple PHP code lets you determine the uptime of a machine in a human-readable format. Of course, you can pull the code apart and do other things with it. First I will start by just giving you the actual code, and then I will explain how it works.

<?php
function getUptime() {
// Calculate server uptime
$uptime = exec("cat /proc/uptime");
$uptime = split(" ", $uptime);
$uptime = $uptime[0];
$secs = intval($uptime % 60);
$mins = intval($uptime / 60 % 60);
$hours = intval($uptime / 3600 % 24);
$days = intval($uptime / 86400);
return($days . " days " . $hours . " hours " . $mins . " minutes " . $secs . " seconds");
}
echo("Server Uptime: " . getUptime()); // display the uptime
?>

The magic sauce that makes this all work is Linux kernel’s interface to get the system uptime: /proc/uptime. The first value it returns is the number of seconds the system has been up, so we split that out and store it in $uptime. The next thing we do is create integers for the days, hours, minutes, and seconds of uptime using a little bit of creative arithmetic. The final process is just a concatenation of the values into a human readable string, and then output it to the page.

Advertisement


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 45 other followers