Show Processor Usage

6

I'm trying to show the use of the server's processor with PHP. Server is Windows with IIS. I've already tried using:

exec("wmic /node:localhost path Win32_Processor where DeviceID='CPU0' get LoadPercentage", $out);

exec("wmic cpu get loadpercentage", $out);

And a few more ways, but it always returns empty. Does anyone know if you need any special permission to do this, or do you have any other ideas?

    
asked by Augusto 06.09.2016 в 15:32
source

2 answers

5

phpSysInfo

One option is to use phpSysInfo

  

Description
  phpSysInfo is a script that shows information about your system.
phpSysInfo >

In addition to showing CPU usage, it shows even more than you need, such as:

  • Memory
  • Ethernet
  • [...] (I left the site link for you to take a look at)

PS: it does not use exec , it reads all information straight from /proc .

Example of what it can do.

sys_getloadavg ()

There is also sys_getloadavg() , which can be a good move.

  

Note
  This function is not implemented on the Windows platform

Font - em English

function retornar_uso_cpu(){

    $uso = sys_getloadavg();
    return $uso[0];     
}
<p><span class="description">Server CPU Usage: </span> <span class="result"><?= retornar_uso_cpu() ?>%</span></p>

Alternative for Windows

An option that works in Windows would be:

  

Note
  This method is not so fast, so be careful about the amount of calls.   If something goes wrong (eg not having sufficient access permissions), it returns 0 .

<?php
function get_server_load() {

        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 {

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

        }

        return (int) $load;

    }
?>
    
answered by 06.09.2016 / 15:41
source
2

First check where the wmic executable is.

  • Go to the windows cmd and type where wmic .
  • In my case I received this response: C:\Windows\System32\wbem\WMIC.exe
  • Then replace your path, if different from mine, in this command: echo shell_exec("C:\Windows\System32\wbem\WMIC.exe cpu get loadpercentage");
  • You will have the response in the browser loadpercentage 19 exactly the same as the response in the terminal window.
  • Other queries .
  • answered by 06.09.2016 в 18:05