How to get CPU usage and RAM usage without exec?

<?php
function get_server_load() 
{
    $load=array();
    if (stristr(PHP_OS, 'win')) 
    {
        $wmi = new COM("Winmgmts://");
        $server = $wmi->execquery("SELECT LoadPercentage FROM Win32_Processor");  
        $cpu_num = 0;
        $load_total = 0;
        foreach($server as $cpu)
        {
            $cpu_num++;
            $load_total += $cpu->loadpercentage;
        }

        $load[]= round($load_total/$cpu_num);

    } 
    else
    {
        $load = sys_getloadavg();
    }
    return $load;
}
echo implode(' ',get_server_load());

This is what I use on Linux servers. It still uses exec, but other questions point here as duplicate, and there is no [good] suggestion for those. It should work on every distro, but if it doesn't, try messing with $get_cores + 1 offset.

CPU in percent of cores used (5 min avg):

$exec_loads = sys_getloadavg();
$exec_cores = trim(shell_exec("grep -P '^processor' /proc/cpuinfo|wc -l"));
$cpu = round($exec_loads[1]/($exec_cores + 1)*100, 0) . '%';

RAM in percent of total used (realtime):

$exec_free = explode("\n", trim(shell_exec('free')));
$get_mem = preg_split("/[\s]+/", $exec_free[1]);
$mem = round($get_mem[2]/$get_mem[1]*100, 0) . '%';

RAM in GB used (realtime):

$exec_free = explode("\n", trim(shell_exec('free')));
$get_mem = preg_split("/[\s]+/", $exec_free[1]);
$mem = number_format(round($get_mem[2]/1024/1024, 2), 2) . '/' . number_format(round($get_mem[1]/1024/1024, 2), 2);

Here is what's in the $get_mem array if you need to calc other facets:

[0]=>row_title [1]=>mem_total [2]=>mem_used [3]=>mem_free [4]=>mem_shared [5]=>mem_buffers [6]=>mem_cached

Bonus, here is how to get the uptime:

$exec_uptime = preg_split("/[\s]+/", trim(shell_exec('uptime')));
$uptime = $exec_uptime[2] . ' Days';

Use PHPSysInfo library

phpSysInfo is a open source PHP script that displays information about the host being accessed. It will displays things like:

  • Uptime
  • CPU
  • Memory
  • SCSI, IDE, PCI
  • Ethernet
  • Floppy
  • Video Information

It directly parsed parses /proc and does not use exec.


Another way is to use Linfo. It is a very fast cross-platform php script that describes the host server in extreme detail, giving information such as ram usage, disk space, raid arrays, hardware, network cards, kernel, os, samba/cups/truecrypt status, temps, disks, and much more.