问题描述
使用PHP,我想获取系统可用的总内存(不仅仅是可用内存或已用内存).
Using PHP, I'd like to get the total memory available to the system (not just the free or used memory).
在Linux上非常简单.您可以这样做:
On Linux it's quite straight forward. You can do:
$memory = fopen('/proc/meminfo');
然后解析文件.
有人知道Windows的等效方法吗?我愿意接受任何建议.
Is anyone aware of an equivalent method for Windows? I'm open to any suggestions.
我们有一个解决方案(但是StackOverflow不允许我回答我自己的问题):
exec( 'systeminfo', $output );
foreach ( $output as $value ) {
if ( preg_match( '|Total Physical Memory\:([^$]+)|', $value, $m ) ) {
$memory = trim( $m[1] );
}
这不是最优雅的解决方案,而且速度很慢,但是很适合我的需求.
Not the most elegant solution, and it's very slow, but it suits my need.
推荐答案
您可以通过exec
执行此操作:
You can do this via exec
:
exec('wmic memorychip get capacity', $totalMemory);
print_r($totalMemory);
这将打印(在我的具有2x2和2x4块RAM的机器上):
This will print (on my machine having 2x2 and 2x4 bricks of RAM):
Array
(
[0] => Capacity
[1] => 4294967296
[2] => 2147483648
[3] => 4294967296
[4] => 2147483648
[5] =>
)
您可以通过使用
echo array_sum($totalMemory);
然后将得到12884901888.要将其转换为千字节,兆字节或千兆字节,请分别除以1024,例如
which will then give 12884901888. To turn this into Kilo-, Mega- or Gigabytes, divide by 1024 each, e.g.
echo array_sum($totalMemory) / 1024 / 1024 / 1024; // GB
查询总RAM的其他命令行方法可以在
Additional command line ways of querying total RAM can be found in
另一种编程方式是通过COM
:
Another programmatic way would be through 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示例的详细信息,请参见:
For details on this COM example, please see:
- http://php.net/manual/en/book.com.php
- MSDN: Constructing a Moniker String
- MSDN: Win32_ComputerSystem class
您可能可以从其他Windows API获得此信息,例如 .NET API..
You can likely get this information from other Windows APIs, like the .NET API., as well.
在Windows上也有PECL扩展名可以做到这一点:
There is also PECL extension to do this on Windows:
根据文档,它应该返回一个数组,其中包含一个名为total_phys
的键,该键对应于"总物理内存量."
According to the documentation, it should return an array which contains (among others) a key named total_phys
which corresponds to "The amount of total physical memory."
但是,由于它是PECL扩展名,因此您首先必须将其安装在计算机上.
But since it's a PECL extension, you'd first have to install it on your machine.
这篇关于在Windows上使用PHP获取可用的系统总内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!