如何在php中显示系统正常运行时间?
作者:互联网
还是一个初学者,所以忍受我…
因此,我发现这个函数用于系统正常运行时间,并且一直在学习php和Web开发时一直在使用它.
我的目标是让输出看起来像天:小时:分钟:秒但是没有$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
);
}
最佳答案:
直接从/ proc / uptime读取是Linux上最有效的解决方案.有多种方法可以将输出转换为天/小时/分钟/秒.尝试类似的东西:
$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;
标签:php,linux,php-5-5 来源: https://codeday.me/bug/20190516/1115084.html