如何使用 php 获取服务器 CPU 使用率和 RAM 使用率?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22949295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:23:41  来源:igfitidea点击:

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

phpcpu-usage

提问by Mehdi Homeily

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

我想使用 php 获取服务器 CPU 和 RAM 使用率。该脚本应该适用于 windows 和 linux。

How would I do that?

我该怎么做?

回答by Snoobih

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:

此函数将返回服务器 CPU 使用情况:

function get_server_cpu_usage(){

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

}

回答by Garreth McDaid

I'd advise using PHP SNMP

我建议使用 PHP SNMP

http://www.php.net/manual/en/book.snmp.php

http://www.php.net/manual/en/book.snmp.php

This will provide a unified solution for both Windows and Linux without have to mess around with exec commands.

这将为 Windows 和 Linux 提供统一的解决方案,而无需处理 exec 命令。

You will of course need to install a Windows SNMP daemon/service on both your Windows and Linux servers

您当然需要在 Windows 和 Linux 服务器上安装 Windows SNMP 守护进程/服务

For Linux, just use Net-SNMP eg CentOS

对于 Linux,只需使用 Net-SNMP,例如 CentOS

sudo yum install net-snmp
sudo service snmpd start
sudo chkconfig snmpd on

Net-SNMP is also available for Windows:

Net-SNMP 也可用于 Windows:

http://www.net-snmp.org/

http://www.net-snmp.org/