题
有没有办法知道在服务器(Linux发行版)用PHP的avaliable RAM(WIDTHOUT使用Linux命令)?
编辑:抱歉,目的是要意识到在服务器/虚拟机中可用的RAM,为特定服务器(即使该存储器是共享的)
。解决方案
如果你知道这个代码将只在Linux下运行,你可以使用特殊/proc/meminfo
文件,以获取有关系统的虚拟内存子系统的信息。该文件具有形式是这样的:
MemTotal: 255908 kB
MemFree: 69936 kB
Buffers: 15812 kB
Cached: 115124 kB
SwapCached: 0 kB
Active: 92700 kB
Inactive: 63792 kB
...
这第一线,MemTotal: ...
,包含在机器物理RAM的数量,减去由内核为它自己的使用而保留的空间。这是我所知道的获得一个Linux系统上可用内存的简单报告的最佳方式。您应该能够通过类似下面的代码来提取它:
<?php
$fh = fopen('/proc/meminfo','r');
$mem = 0;
while ($line = fgets($fh)) {
$pieces = array();
if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $pieces)) {
$mem = $pieces[1];
break;
}
}
fclose($fh);
echo "$mem kB RAM found"; ?>
(请注意:此代码可能需要一些调整您的环境)
其他提示
使用/proc/meminfo
和获取一切成阵列是简单的:
<?php
function getSystemMemInfo()
{
$data = explode("\n", file_get_contents("/proc/meminfo"));
$meminfo = array();
foreach ($data as $line) {
list($key, $val) = explode(":", $line);
$meminfo[$key] = trim($val);
}
return $meminfo;
}
?>
var_dump( getSystemMemInfo() );
array(43) {
["MemTotal"]=>
string(10) "2060700 kB"
["MemFree"]=>
string(9) "277344 kB"
["Buffers"]=>
string(8) "92200 kB"
["Cached"]=>
string(9) "650544 kB"
["SwapCached"]=>
string(8) "73592 kB"
["Active"]=>
string(9) "995988 kB"
...
可使用href="http://us1.php.net/function.exec" rel="noreferrer">在PHP EXEC 功能
尝试使用以下代码:<?php
exec("free -mtl", $output);
print_r($output);
?>
值得注意的是,在Windows中,这个信息(和更多)可以通过执行和解析外壳命令的输出获得的:系统的系统
我不认为你可以访问主机服务器的内存信息没有特殊的书面PHP扩展。 PHP核心库不允许(可能出于安全原因)来访问扩展内存信息。
不过,如果你的脚本可以访问/proc/meminfo
那么你可以查询特殊文件,并抓住你所需要的信息。在Windows上(尽管你不问它已经),我们可以使用com_dotnet
PHP扩展通过COM查询Windows的框架。
下面你可以找到我的getSystemMemoryInfo
如果你运行的Linux / Windows服务器上的脚本,返回的信息对你没有关系。所述wmiWBemLocatorQuery
只是一个辅助函数。
function wmiWBemLocatorQuery( $query ) {
if ( class_exists( '\\COM' ) ) {
try {
$WbemLocator = new \COM( "WbemScripting.SWbemLocator" );
$WbemServices = $WbemLocator->ConnectServer( '127.0.0.1', 'root\CIMV2' );
$WbemServices->Security_->ImpersonationLevel = 3;
// use wbemtest tool to query all classes for namespace root\cimv2
return $WbemServices->ExecQuery( $query );
} catch ( \com_exception $e ) {
echo $e->getMessage();
}
} elseif ( ! extension_loaded( 'com_dotnet' ) )
trigger_error( 'It seems that the COM is not enabled in your php.ini', E_USER_WARNING );
else {
$err = error_get_last();
trigger_error( $err['message'], E_USER_WARNING );
}
return false;
}
// _dir_in_allowed_path this is your function to detect if a file is withing the allowed path (see the open_basedir PHP directive)
function getSystemMemoryInfo( $output_key = '' ) {
$keys = array( 'MemTotal', 'MemFree', 'MemAvailable', 'SwapTotal', 'SwapFree' );
$result = array();
try {
// LINUX
if ( ! isWin() ) {
$proc_dir = '/proc/';
$data = _dir_in_allowed_path( $proc_dir ) ? @file( $proc_dir . 'meminfo' ) : false;
if ( is_array( $data ) )
foreach ( $data as $d ) {
if ( 0 == strlen( trim( $d ) ) )
continue;
$d = preg_split( '/:/', $d );
$key = trim( $d[0] );
if ( ! in_array( $key, $keys ) )
continue;
$value = 1000 * floatval( trim( str_replace( ' kB', '', $d[1] ) ) );
$result[$key] = $value;
}
} else // WINDOWS
{
$wmi_found = false;
if ( $wmi_query = wmiWBemLocatorQuery(
"SELECT FreePhysicalMemory,FreeVirtualMemory,TotalSwapSpaceSize,TotalVirtualMemorySize,TotalVisibleMemorySize FROM Win32_OperatingSystem" ) ) {
foreach ( $wmi_query as $r ) {
$result['MemFree'] = $r->FreePhysicalMemory * 1024;
$result['MemAvailable'] = $r->FreeVirtualMemory * 1024;
$result['SwapFree'] = $r->TotalSwapSpaceSize * 1024;
$result['SwapTotal'] = $r->TotalVirtualMemorySize * 1024;
$result['MemTotal'] = $r->TotalVisibleMemorySize * 1024;
$wmi_found = true;
}
}
// TODO a backup implementation using the $_SERVER array
}
} catch ( Exception $e ) {
echo $e->getMessage();
}
return empty( $output_key ) || ! isset( $result[$output_key] ) ? $result : $result[$output_key];
}
一个8GB RAM系统上示例强>
print_r(getSystemMemoryInfo());
<强>输出强>
Array
(
[MemTotal] => 8102684000
[MemFree] => 2894508000
[MemAvailable] => 4569396000
[SwapTotal] => 4194300000
[SwapFree] => 4194300000
)
如果您想了解每个字段表示随后的读详情。
//助手
/**
* @return array|null
*/
protected function getSystemMemInfo()
{
$meminfo = @file_get_contents("/proc/meminfo");
if ($meminfo) {
$data = explode("\n", $meminfo);
$meminfo = [];
foreach ($data as $line) {
if( strpos( $line, ':' ) !== false ) {
list($key, $val) = explode(":", $line);
$val = trim($val);
$val = preg_replace('/ kB$/', '', $val);
if (is_numeric($val)) {
$val = intval($val);
}
$meminfo[$key] = $val;
}
}
return $meminfo;
}
return null;
}
// example call to check health
public function check() {
$memInfo = $this->getSystemMemInfo();
if ($memInfo) {
$totalMemory = $memInfo['MemTotal'];
$freeMemory = $memInfo['MemFree'];
$swapTotalMemory = $memInfo['SwapTotal'];
$swapFreeMemory = $memInfo['SwapFree'];
if (($totalMemory / 100.0) * 30.0 > $freeMemory) {
if (($swapTotalMemory / 100.0) * 50.0 > $swapFreeMemory) {
return new Failure('Less than 30% free memory and less than 50% free swap space');
}
return new Warning('Less than 30% free memory');
}
}
return new Success('ok');
}
较短版本
preg_match('#MemFree:[\s\t]+([\d]+)\s+kB#', file_get_contents('/proc/meminfo'), $matches);
var_dump($matches[1]); // Free abount in KB
我不记得有见过这样的功能 - 它的那种出了什么PHP是由范围,实际上
即使有这样的functionnality,它可能会在某种程度上这将是特定于底层的操作系统中实现,而不会大概就Linux和Windows工作的(见的对于这种事情的一例sys_getloadavg
)