0

I have (for example) this:

ini_set('memory_limit', '128M');

It varies between scripts and settings. I need to get the number of bytes -- not the string '128M' -- at runtime.

I have no use of the string 128M, and do not wish to code my own parser to turn that (and all other symbols supported) into bytes.

How do I get the raw maximum number of bytes currently allowed for the current script?

(I'm coding a mechanism which is going to notify me when a script approaches its maximum allowed RAM usage, prior to it exceeding this, in order to send useful health reports to myself. Once it's already hit the roof, there is a FATAL error and it doesn't log properly.)

user17535142
  • 71
  • 1
  • 6
  • For what it's worth, there're only three [suffixes](https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes) and they're won't change without prior advice. It's going to be an extremely simple parser. – Álvaro González Dec 03 '21 at 17:48

1 Answers1

0
function conv2bytes($val) {
    $val = strtolower(trim($val));

    $unit = substr($val,-1, 1);
    $val = substr($val, 0, -1);

    if($unit=='g') $val *= 1024*1024*1024;
    else if($unit=='m') $val *= 1024*1024;
    else if($unit=='k') $val *= 1024;
    else return false;
    return $val;
}

And use the code below to get the ram usage

echo memory_get_usage(false); // only the used memory is reported
echo memory_get_usage(true); // get total memory allocated from system, including unused pages

Reference: https://www.php.net/manual/en/function.memory-get-usage.php

Alpaca0x0
  • 45
  • 6
  • This is exactly the kind of answer I explicitly said I didn't want. You are assuming that megabytes are always used, it's ugly, it's fragile, etc. – user17535142 Dec 03 '21 at 04:14
  • Sorry, maybe you should try to set the fomat you want at the beginning? like... `ini_set('memory_limit', 512000000);` Then when you use `ini_set()`, it will return the format you set. – Alpaca0x0 Dec 03 '21 at 04:26
  • Yes, but then that requires the user to use that very human-unfriendly format. This needs to be independent of how the user set it. – user17535142 Dec 03 '21 at 04:55
  • uh... except this, I have no idea temporarily :( – Alpaca0x0 Dec 03 '21 at 05:03
  • I did find this, but it's just more of the same user-defined madness functions: https://stackoverflow.com/questions/11807115/php-convert-kb-mb-gb-tb-etc-to-bytes – user17535142 Dec 03 '21 at 05:04
  • Nevermind. I've concluded that this is yet another "lost cause". I'll just use bytes. Sigh. – user17535142 Dec 03 '21 at 07:34