在 PHP 中检查 memory_limit

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10208698/
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-24 21:39:28  来源:igfitidea点击:

checking memory_limit in PHP

phpmemory-limit

提问by Spacedust

I'm need to check if memory_limitis at least 64Min my script installer. This is just part of PHP code that should work, but probably due to this "M" it's not reading properly the value. How to fix this ?

我需要检查是否memory_limit至少64M在我的脚本安装程序中。这只是应该工作的 PHP 代码的一部分,但可能由于这个“M”,它没有正确读取值。如何解决这个问题?

  //memory_limit
    echo "<phpmem>";
    if(key_exists('PHP Core', $phpinfo))
    {
        if(key_exists('memory_limit', $phpinfo['PHP Core']))
        {
            $t=explode(".", $phpinfo['PHP Core']['memory_limit']);
            if($t[0]>=64)
                $ok=1;
            else
                $ok=0;
            echo "<val>{$phpinfo['PHP Core']['memory_limit']}</val><ok>$ok</ok>";
        }
        else
           echo "<val></val><ok>0</ok>";
    }
    else
        echo "<val></val><ok>0</ok>";
    echo "</phpmem>\n"; 

采纳答案by Muhammad Alvin

Try to convert the value first (eg: 64M -> 64 * 1024 * 1024). After that, do comparison and print the result.

尝试先转换值(例如:64M -> 64 * 1024 * 1024)。之后,进行比较并打印结果。

<?php
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
    if ($matches[2] == 'M') {
        $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
    } else if ($matches[2] == 'K') {
        $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
    }
}

$ok = ($memory_limit >= 64 * 1024 * 1024); // at least 64M?

echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';

Please note that the above code is just an idea.Don't forget to handle -1 (no memory limit), integer-only value (value in bytes), G (value in gigabytes), k/m/g (value in kilobytes, megabytes, gigabytes because shorthand is case-insensitive), etc.

请注意,上面的代码只是一个想法。不要忘记处理 -1(无内存限制)、仅整数值(以字节为单位的值)、G(以千兆字节为单位的值)、k/m/g(以千字节、兆字节、千兆字节为单位的值,因为速记不区分大小写), 等等。

回答by Okan

Checking on command line:

在命令行上检查:

php -i | grep "memory_limit"

回答by Ulver

Here is another simpler way to check that.

这是另一种更简单的检查方法。

$memory_limit = return_bytes(ini_get('memory_limit'));
if ($memory_limit < (64 * 1024 * 1024)) {
    // Memory insufficient      
}

/**
* Converts shorthand memory notation value to bytes
* From http://php.net/manual/en/function.ini-get.php
*
* @param $val Memory size shorthand notation string
*/
function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $val = substr($val, 0, -1);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}

回答by Gibz

very old post. but i'll just leave this here:

很老的帖子。但我会把这个留在这里:

/* converts a number with byte unit (B / K / M / G) into an integer */
function unitToInt($s)
{
    return (int)preg_replace_callback('/(\-?\d+)(.?)/', function ($m) {
        return $m[1] * pow(1024, strpos('BKMG', $m[2]));
    }, strtoupper($s));
}

$mem_limit = unitToInt(ini_get('memory_limit'));

回答by hakre

As long as your array $phpinfo['PHP Core']['memory_limit']contains the value of memory_limit, it does work the following:

只要您的数组$phpinfo['PHP Core']['memory_limit']包含 的值memory_limit,它就会执行以下操作:

  • The last character of that value can signal the shorthand notation. If it's an invalid one, it's ignored.
  • The beginning of the string is converted to a number in PHP's own specific way: Whitespace ignored etc.
  • The text between the number and the shorthand notation (if any) is ignored.
  • 该值的最后一个字符可以表示速记符号。如果它是无效的,则将其忽略。
  • 字符串的开头以 PHP 自己的特定方式转换为数字:忽略空格等。
  • 数字和速记符号(如果有)之间的文本将被忽略。

Example:

例子:

# Memory Limit equal or higher than 64M?
$ok = (int) (bool) setting_to_bytes($phpinfo['PHP Core']['memory_limit']) >= 0x4000000;

/**
 * @param string $setting
 *
 * @return NULL|number
 */
function setting_to_bytes($setting)
{
    static $short = array('k' => 0x400,
                          'm' => 0x100000,
                          'g' => 0x40000000);

    $setting = (string)$setting;
    if (!($len = strlen($setting))) return NULL;
    $last    = strtolower($setting[$len - 1]);
    $numeric = (int) $setting;
    $numeric *= isset($short[$last]) ? $short[$last] : 1;
    return $numeric;
}

Details of the shorthand notation are outline in a PHP manual's FAQ entryand extreme details are part of Protocol of some PHP Memory Stretching Fun.

速记符号的详细信息在PHP 手册的 FAQ 条目中概述,极端细节是某些 PHP Memory Stretching Fun协议的一部分

Take care if the setting is -1PHP won't limit here, but the system does. So you need to decide how the installer treats that value.

注意如果设置为-1PHP 不会限制在这里,但系统会限制。因此,您需要决定安装程序如何处理该值。

回答by OZZIE

If you are interested in CLI memory limit:

如果您对 CLI 内存限制感兴趣:

cat /etc/php/[7.0]/cli/php.ini | grep "memory_limit"

FPM / "Normal"

FPM/“正常”

cat /etc/php/[7.0]/fpm/php.ini | grep "memory_limit"

回答by Jared Chu

Command line to check ini:

检查ini的命令行:

$ php -r "echo ini_get('memory_limit');"

回答by Rauli Rajande

Not so exact but simpler solution:

不是那么精确但更简单的解决方案:

$limit = str_replace(array('G', 'M', 'K'), array('000000000', '000000', '000'), ini_get('memory_limit'));
if($limit < 500000000) ini_set('memory_limit', '500M');                     

回答by Ivan Kvasnica

Thank you for inspiration.

谢谢你的灵感。

I had the same problem and instead of just copy-pasting some function from the Internet, I wrote an open source tool for it. Feel free to use it or provide feedback!

我遇到了同样的问题,我没有从 Internet 上复制粘贴一些函数,而是为它编写了一个开源工具。随意使用它或提供反馈!

https://github.com/BrandEmbassy/php-memory

https://github.com/BrandEmbassy/php-memory

Just install it using Composer and then you get the current PHP memory limit like this:

只需使用 Composer 安装它,然后您就会获得当前的 PHP 内存限制,如下所示:

$configuration = new \BrandEmbassy\Memory\MemoryConfiguration();
$limitProvider = new \BrandEmbassy\Memory\MemoryLimitProvider($configuration);
$limitInBytes = $memoryLimitProvider->getLimitInBytes();