使用 php 获取服务器 RAM

发布于 2024-08-05 22:44:09 字数 103 浏览 5 评论 0原文

有没有办法用php(使用linux命令的宽度)知道服务器(linux发行版)中的可用内存?

编辑:抱歉,目标是了解特定服务器的服务器/虚拟机中可用的内存(即使该内存是共享的)。

Is there a way to know the avaliable ram in a server (linux distro) with php (widthout using linux commands)?

edit: sorry, the objective is to be aware of the ram available in the server / virtual machine, for the particular server (even if that memory is shared).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

节枝 2024-08-12 22:44:09

如果您知道此代码只能在 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"; ?>

请注意:此代码可能需要针对您的环境进行一些调整。)

If you know this code will only be running under Linux, you can use the special /proc/meminfo file to get information about the system's virtual memory subsystem. The file has a form like this:

MemTotal:       255908 kB
MemFree:         69936 kB
Buffers:         15812 kB
Cached:         115124 kB
SwapCached:          0 kB
Active:          92700 kB
Inactive:        63792 kB
...

That first line, MemTotal: ..., contains the amount of physical RAM in the machine, minus the space reserved by the kernel for its own use. It's the best way I know of to get a simple report of the usable memory on a Linux system. You should be able to extract it via something like the following code:

<?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"; ?>

(Please note: this code may require some tweaking for your environment.)

橘亓 2024-08-12 22:44:09

使用 /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"
  ...

Using /proc/meminfo and getting everything into an array is simple:

<?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"
  ...
独﹏钓一江月 2024-08-12 22:44:09

Linux 命令可以使用 PHP 中的 exec 函数运行。这是有效的并且可以完成工作(如果目标是获得内存)。

尝试以下代码:

<?php
  exec("free -mtl", $output);
  print_r($output);
?>

Linux commands can be run using the exec function in PHP. This is efficient and will do the job(if objective is to get the memory).

Try the following code:

<?php
  exec("free -mtl", $output);
  print_r($output);
?>
暖风昔人 2024-08-12 22:44:09

小而整洁的函数,用于获取与其键关联的所有值。

$contents = file_get_contents('/proc/meminfo');
preg_match_all('/(\w+):\s+(\d+)\s/', $contents, $matches);
$info = array_combine($matches[1], $matches[2]);

// $info['MemTotal'] = "2047442"

Small and tidy function to get all of its values associated to their keys.

$contents = file_get_contents('/proc/meminfo');
preg_match_all('/(\w+):\s+(\d+)\s/', $contents, $matches);
$info = array_combine($matches[1], $matches[2]);

// $info['MemTotal'] = "2047442"
二智少女 2024-08-12 22:44:09

我认为如果没有专门编写的 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
)

如果您想了解每个字段代表什么,那么 了解更多

I don't think you can access the host server memory info without a special written PHP extension. The PHP core library does not allow (perhaps for security reasons) to access the extended memory info.

However, if your script has access to the /proc/meminfo then you can query that special file and grab the info you need. On Windows (although you've not asked for it) we can use the com_dotnet PHP extension to query the Windows framework via COM.

Below you can find my getSystemMemoryInfo that returns that info for you no matter if you run the script on a Linux/Windows server. The wmiWBemLocatorQuery is just a helper function.

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];
}

Example on a 8GB RAM system

print_r(getSystemMemoryInfo());

Output

Array
(
    [MemTotal] => 8102684000
    [MemFree] => 2894508000
    [MemAvailable] => 4569396000
    [SwapTotal] => 4194300000
    [SwapFree] => 4194300000
)

If you want to understand what each field represent then read more.

恰似旧人归 2024-08-12 22:44:09

exec("grep MemTotal /proc/meminfo", $aryMem);
$aryMem[0] 是您的总内存减去内核使用量。

exec("grep MemTotal /proc/meminfo", $aryMem);
$aryMem[0] has your total ram minus kernel usage.

羞稚 2024-08-12 22:44:09

值得注意的是,在 Windows 中,可以通过执行和解析 shell 命令的输出来获取此信息(以及更多信息):systeminfo

It is worth noting that in Windows this information (and much more) can be acquired by executing and parsing the output of the shell command: systeminfo

花开浅夏 2024-08-12 22:44:09

我不记得曾经见过这样的函数——实际上,它超出了 PHP 的用途范围。

即使有这样的功能,它也可能以特定于底层操作系统的方式实现,并且可能无法在 Linux 和 Windows 上工作(请参阅 sys_getloadavg 是此类事情的示例)

I don't remember having ever seen such a function -- its kind of out the scope of what PHP is made for, actually.

Even if there was such a functionnality, it would probably be implemented in a way that would be specific to the underlying operating system, and wouldn't probably work on both Linux and windows (see sys_getloadavg for an example of that kind of thing)

梦里兽 2024-08-12 22:44:09

// 助手

/**
 * @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');
}

// helpers

/**
 * @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');
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文