How do you get server CPU usage and RAM usage with php?

Mehdi Homeily picture Mehdi Homeily · Apr 9, 2014 · Viewed 70k times · Source

I want to get server CPU and RAM usage using php. The script should work on windows and linux.

How would I do that?

Answer

Snoobih picture Snoobih · Apr 9, 2014

The first function will return the Server Memory Usage:

function get_server_memory_usage(){

    $free = shell_exec('free');
    $free = (string)trim($free);
    $free_arr = explode("\n", $free);
    $mem = explode(" ", $free_arr[1]);
    $mem = array_filter($mem);
    $mem = array_merge($mem);
    $memory_usage = $mem[2]/$mem[1]*100;

    return $memory_usage;
}

This function will return the Server CPU Usage:

function get_server_cpu_usage(){

    $load = sys_getloadavg();
    return $load[0];

}