Ethan Morris Ethan Morris - 3 months ago 39
Linux Question

How to display system uptime in php?

Still a beginner so bear with me...

So I found this function for system uptime and have been fooling around with it as I learn about php and web development in general.

My goal is to have the output look like days:hours:mins:secs but there was no $seconds variable so I have added that line based on what else I had.
Everything works great except the seconds just shows up as 0. I'm not quite sure what I am doing wrong or if this is even the best way to do this.

function Uptime() {

$uptime = @file_get_contents( "/proc/uptime");

$uptime = explode(" ",$uptime);
$uptime = $uptime[0];
$days = explode(".",(($uptime % 31556926) / 86400));
$hours = explode(".",((($uptime % 31556926) % 86400) / 3600));
$minutes = explode(".",(((($uptime % 31556926) % 86400) % 3600) / 60));
$seconds = explode(".",((((($uptime % 31556926) % 86400) % 3600) / 60) / 60));

$time = $days[0].":".$hours[0].":".$minutes[0].":".$seconds[0];

return $time;

}


EDIT: I was able to get it working in a different way new function is below .
I am also still curious if anyone can answer why the above method did not work as expected, and if the new method below is the best way to accomplish this.

function Uptime() {
$ut = strtok( exec( "cat /proc/uptime" ), "." );
$days = sprintf( "%2d", ($ut/(3600*24)) );
$hours = sprintf( "%2d", ( ($ut % (3600*24)) / 3600) );
$min = sprintf( "%2d", ($ut % (3600*24) % 3600)/60 );
$sec = sprintf( "%2d", ($ut % (3600*24) % 3600)%60 );


return array( $days, $hours, $min, $sec );
}
$ut = Uptime();
echo "Uptime: $ut[0]:$ut[1]:$ut[2]:$ut[3]";

Answer

uptime supports the -p command line option. You can use this simple piece of code:

echo shell_exec('uptime -p');