使用PHP,我想获得系统可用的总内存(而不仅仅是空闲或已使用的内存)。
在Linux上非常直接。你可以这样做:
$memory = fopen('/proc/meminfo');
,然后解析文件。
有谁知道Windows的等效方法吗?我愿意接受任何建议。
编辑:我们有一个解决方案(但StackOverflow不会让我回答我自己的问题):
exec( 'systeminfo', $output );
foreach ( $output as $value ) {
if ( preg_match( '|Total Physical Memory':([^$]+)|', $value, $m ) ) {
$memory = trim( $m[1] );
}
不是最优雅的解决方案,而且速度很慢,但它符合我的需要。
您可以通过exec
:
exec('wmic memorychip get capacity', $totalMemory);
print_r($totalMemory);
这将打印(在我的机器上有2x2和2x4块RAM):
Array
(
[0] => Capacity
[1] => 4294967296
[2] => 2147483648
[3] => 4294967296
[4] => 2147483648
[5] =>
)
可以使用
将其相加echo array_sum($totalMemory);
将返回12884901888。要将其转换为千字节、兆字节或千兆字节,分别除以1024,例如
echo array_sum($totalMemory) / 1024 / 1024 / 1024; // GB
查询总RAM的其他命令行方法可以在
中找到- https://superuser.com/questions/315195/is-there-a-command-to-find-out-the-available-memory-in-windows
另一种编程方式是通过COM
:
// connect to WMI
$wmi = new COM('WinMgmts:root/cimv2');
// Query this Computer for Total Physical RAM
$res = $wmi->ExecQuery('Select TotalPhysicalMemory from Win32_ComputerSystem');
// Fetch the first item from the results
$system = $res->ItemIndex(0);
// print the Total Physical RAM
printf(
'Physical Memory: %d MB',
$system->TotalPhysicalMemory / 1024 /1024
);
有关此COM示例的详细信息,请参见:
- http://php.net/manual/en/book.com.php
- MSDN:构造一个名字字符串
- MSDN: Win32_ComputerSystem类
你可以从其他的Windows API(比如。net API)中得到这些信息。
也有PECL扩展在Windows上做到这一点:
- win32_ps_stat_mem -检索全局内存利用率的统计信息。
根据文档,它应该返回一个数组,其中包含(除其他外)一个名为total_phys
的键,该键对应于"物理内存总量。"
但是因为它是一个PECL扩展,你必须首先在你的机器上安装它。
这是一个次要的区别(可能更适合超级用户),但由于我在最近的windows服务中遇到了它,所以我将在这里提供它。问题问的是可用内存,而不是总物理内存。
exec('wmic OS get FreePhysicalMemory /Value 2>&1', $output, $return);
$memory = substr($output[2],19);
echo $memory;