Calculating Sever Uptime in PHP
Posted: December 22, 2007 Filed under: NEZzen Leave a comment »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
