Created
August 31, 2019 05:08
-
-
Save lakuapik/dee5fc4585f1f8a7c64a6ae3cdf0f4a7 to your computer and use it in GitHub Desktop.
Get uptime, memory usage, cpu usage and disk usage on GNU/Linux server using PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
header('Content-Type: application/json'); | |
function get_uptime() | |
{ | |
$str = @file_get_contents('/proc/uptime'); | |
$num = floatval($str); | |
$secs = (int) fmod($num, 60); $num = intdiv($num, 60); | |
$mins = $num % 60; $num = intdiv($num, 60); | |
$hours = $num % 24; $num = intdiv($num, 24); | |
$days = $num; | |
return "$days day $hours hour $mins min $secs sec"; | |
} | |
function get_server_memory_usage() | |
{ | |
$free = shell_exec('free -mh'); | |
$free = (string)trim($free); | |
$free_arr = explode("\n", $free); | |
$mem = explode(" ", $free_arr[1]); | |
$mem = array_filter($mem); | |
$mem = array_merge($mem); | |
return $mem; | |
} | |
function get_server_cpu_usage() | |
{ | |
return trim(shell_exec("grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage \"%\"}'")); | |
} | |
function format_b($bytes) | |
{ | |
return round(($bytes / (1024 * 1024 * 1024)), 2).'GB'; | |
} | |
$memory = get_server_memory_usage(); | |
$data = [ | |
'uptime' => get_uptime(), | |
'memory_total' => $memory[1], | |
'memory_used' => $memory[2], | |
'memory_free' => $memory[3], | |
'cpu' => get_server_cpu_usage(), | |
'disk_total' => format_b(disk_total_space('/')), | |
'disk_free' => format_b(disk_free_space('/')), | |
]; | |
echo json_encode($data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment