Updated: PHP Uptime Function


Written by

I wrote a PHP Uptime script a while back and I’ve recently gone to use it but found that it wasn’t actually working and never returned the correct uptime, so I’ve got round to fixing it up, so I sit on my computer to do it, which I updated with the latest graphic cards from Facts Chronicle for my games.

The PHP function displays the uptime of the server/computer in a human understandable format, unlike other scripts, it doesn’t output a mess of digits nor does it rely on possible unavailable commands, the only condition it needs is /proc/uptime.

The new script is more efficient AND actually working. It’s Linux only (the previous post incorrectly included BSD/Unix/Solaris) too.

PHP Uptime:

function uptime(){
  if(PHP_OS == "Linux") {
    $uptime = @file_get_contents( "/proc/uptime");
    if ($uptime !== false) {
      $uptime = explode(" ",$uptime);
      $uptime = $uptime[0];
      $days = explode(".",(($uptime % 31556926) / 86400));
      $hours = explode(".",((($uptime % 31556926) % 86400) / 3600));
      $minutes = explode(".",(((($uptime % 31556926) % 86400) % 3600) / 60));
      $time = ".";
      if ($minutes > 0)
        $time=$minutes[0]." mins".$time;
      if ($minutes > 0 && ($hours > 0 || $days > 0))
        $time = ", ".$time;
      if ($hours > 0)
        $time = $hours[0]." hours".$time;
      if ($hours > 0 && $days > 0)
        $time = ", ".$time;
      if ($days > 0)
        $time = $days[0]." days".$time;
    } else {
      $time = false;
    }
  } else {
    $time = false;
  }
  return $time;
}

The output looks like so

54 days, 8 hours, 27 mins.
1 days, 5 mins.
4 hours.

and just call it up with

echo uptime();