php如何显示系统正常运行时间?

How to display system uptime in php?

还是初学者,多多包涵...
所以我发现了这个用于系统正常运行时间的功能,并且在我了解 php 和一般的 Web 开发时一直在玩弄它。
我的目标是使输出看起来像 days:hours:mins:secs 但没有 $seconds 变量,所以我根据其他内容添加了该行。 一切都很好,除了秒数显示为 0。我不太确定我做错了什么,或者这是否是最好的方法。

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;

}

编辑:我能够以不同的方式让它工作,下面是新功能。 我也很好奇是否有人可以回答为什么上述方法没有按预期工作,以及下面的新方法是否是实现此目的的最佳方法。

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]";

编辑 2:根据 nwellnhof 给出的答案,我认为最后一种方法是最好的。我不得不稍微调整一下才能得到我想要的输出。谢谢大家。

function Uptime() {
        $str   = @file_get_contents('/proc/uptime');
        $num   = floatval($str);
        $secs  = $num % 60;
        $num   = (int)($num / 60);
        $mins  = $num % 60;
        $num   = (int)($num / 60);
        $hours = $num % 24;
        $num   = (int)($num / 24);
        $days  = $num;

        return array(
            "days"  => $days,
            "hours" => $hours,
            "mins"  => $mins,
            "secs"  => $secs
        );
    }

uptime 支持 -p 命令行选项。您可以使用这段简单的代码:

echo shell_exec('uptime -p');

直接从 /proc/uptime 读取是 Linux 上最有效的解决方案。有多种方法可以将输出转换为 days/hours/minutes/seconds。尝试类似的东西:

$str   = @file_get_contents('/proc/uptime');
$num   = floatval($str);
$secs  = fmod($num, 60); $num = (int)($num / 60);
$mins  = $num % 60;      $num = (int)($num / 60);
$hours = $num % 24;      $num = (int)($num / 24);
$days  = $num;

或者,intdiv (PHP7):

$str   = @file_get_contents('/proc/uptime');
$num   = floatval($str);
$secs  = fmod($num, 60); $num = intdiv($num, 60);
$mins  = $num % 60;      $num = intdiv($num, 60);
$hours = $num % 24;      $num = intdiv($num, 24);
$days  = $num;

如果你只看一下语句中的模式,你会发现秒数是不同的。它有两个部门。此外,您使用的数字表示每个时间单位的秒数。每秒的秒数应该是1,而不是60。简而言之:

$seconds = explode(".",((((($uptime % 31556926) % 86400) % 3600) / 60) / 60));

应该是:

$seconds = explode(".",((((($uptime % 31556926) % 86400) % 3600) % 60) / 1));

现在整个做事方式有点奇怪。例如,(x % (n*m)) % m 就是 x % m.

更好的方法是:

$uptime  = (int) $uptime;
$seconds =  $uptime               % 60;
$minutes = ($uptime /  60       ) % 60;
$hours   = ($uptime / (60*60)   ) % 24;
$days    =  $uptime / (60*60*24); # % 365, if you want

初始示例的变体 class:

class Uptime {
    private $uptime;

    private $modVals = array(31556926, 86400, 3600, 60, 60);

    public function __construct() {
        $this->read_uptime();
    }

    /**
     * actually trigger a read of the system clock and cache the value
     * @return string
     */
    private function read_uptime() {
        $uptime_raw = @file_get_contents("/proc/uptime");
        $this->uptime = floatval($uptime_raw);
        return $this->uptime;
    }

    private function get_uptime_cached() {
        if(is_null($this->uptime)) $this->read_uptime(); // only read if not yet stored or empty
        return $this->uptime;
    }

    /**
     * recursively run mods on time value up to given depth
     * @param int $d
     * @return int
     **/
    private function doModDep($d) {
        $start = $this->get_uptime_cached();
        for($i=0;$i<$d;$i++) {
            $start = $start % $this->modVals[$i];
        }
        return intval($start / $this->modVals[$d]);
    }

    public function getDays()
    {
        return $this->doModDep(1);
    }

    public function getHours() {
        return $this->doModDep(2);
    }

    public function getMinutes()
    {
        return $this->doModDep(3);
    }

    public function getSeconds()
    {
        return $this->doModDep(4);
    }

    public function getTime($cached=false) {
        if($cached != false) $this->read_uptime(); // resample cached system clock value
        return sprintf("%03d:%02d:%02d:%02d", $this->getDays(), $this->getHours(), $this->getMinutes(), $this->getSeconds());
    }
}

在 Unix/BSD 上,使用 /proc 是不可靠的,因为它不是默认安装的,在一些 Linux 发行版上它也可以被卸载,所以最好使用任何一个来解析uptimesysctl 命令,例如

sysctl

<?php
preg_match('/sec = (\d+)/', shell_exec('sysctl -n kern.boottime'), $secs)
echo $secs[1];

或:

$s = explode( " ", exec("/sbin/sysctl -n kern.boottime") );
$a = str_replace( ",", "", $s[3]);
$uptime = time() - $a;  

或根据取自 m0n0wall 的示例:

<?php
exec("/sbin/sysctl -n kern.boottime", $boottime);
preg_match("/sec = (\d+)/", $boottime[0], $matches);
$boottime = $matches[1];
$uptime = time() - $boottime;

if ($uptime > 60)
    $uptime += 30;
$updays = (int)($uptime / 86400);
$uptime %= 86400;
$uphours = (int)($uptime / 3600);
$uptime %= 3600;
$upmins = (int)($uptime / 60);

$uptimestr = "";
if ($updays > 1)
    $uptimestr .= "$updays days, ";
else if ($updays > 0)
    $uptimestr .= "1 day, ";
$uptimestr .= sprintf("%02d:%02d", $uphours, $upmins);
echo htmlspecialchars($uptimestr);

uptime

示例取自 4webhelp

<?php
$data = shell_exec('uptime');
$uptime = explode(' up ', $data);
$uptime = explode(',', $uptime[1]);
$uptime = $uptime[0].', '.$uptime[1];
echo ('Current server uptime: '.$uptime.'

或(在 FreeBSD 上测试):

$uptime = exec("uptime");
$uptime = split(" ",$uptime);
$days = $uptime[3]; # NetBSD: $days = $uptime[4];
$time = split(",",$uptime[5]); # NetBSD: $time = split(",",$uptime[7]);
if (sizeof($hourmin = split(":",$time[0])) < 2){ ;
  $hours = "0";
  $mins = $hourmin[0];
} else {
  $hourmin=split(":",$time[0]);
  $hours = $hourmin[0];
  $mins = $hourmin[1];
}
$calcuptime =  "Uptime: ".$days." days ".$hours." hours ".$mins." mins" ;
echo $calcuptime;

这是适用于 Windows 的版本:

<?php
$uptime = `c:\windows\system32\uptime2.bat $server`;
$uptime = explode(": ", $uptime);
$uptime = explode(", ", $uptime[1]);

$uptime_days = preg_replace($pattern, '', $uptime[0]);
$uptime_hours = preg_replace($pattern, '', $uptime[1]);
$uptime_minutes = preg_replace($pattern, '', $uptime[2]);
$uptime_seconds = preg_replace($pattern, '', $uptime[3]);

echo '<b>Uptime:</b><br><br>';

echo 'Days: '.$uptime_days.'<br>';
echo 'Hours: '.$uptime_hours.'<br>';
echo 'Minutes: '.$uptime_minutes.'<br>';
echo 'Seconds: '.$uptime_seconds.'<br>';