6

I'm currently using the memory_get_usage function to determine how much memory my PHP script is using. However, I want to display the memory usage value against the total amount of memory available to PHP.

How to I get the total amount of memory available to PHP?

Luke
  • 20,878
  • 35
  • 119
  • 178

3 Answers3

12

You can use the php.ini setting memory_limit:

ini_get('memory_limit');

Technically, this is not the total amount available to PHP, it's the amount available to a PHP script.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • 2
    Or if he need total RAM - http://stackoverflow.com/questions/1455379/get-server-ram-with-php – Pavel Dec 29 '13 at 22:30
  • @ComFreek Thanks. When you say "the amount available to a PHP script" I assume you mean that if you set the limit to e.g. 8MB and you're receiving 100 requests at the same time that the total machine memory usage will be 800MB? Correct? – Luke Dec 29 '13 at 22:42
  • 1
    @Luke Quoting the [PHP docs](http://php.net/manual/ini.core.php#ini.memory-limit): "This sets the maximum amount of memory in bytes that a script is allowed to allocate". If 100 requests theoretically run in parallel, and all allocate 100 MB memory (provided that `memory_limit >= 100M`), then the total memory in use will be 800MB. – ComFreek Dec 30 '13 at 09:14
  • 1
    What if the `memory_limit` is set to `-1` that means unlimited... Then you can't work with this solution. – algorhythm Oct 07 '16 at 10:05
1

There is a problem that by using ini_get you'll get just the string from php.ini (e.g. 500 or 500M or 1G etc.).

Should you need the real value in bytes, you can use this simple open source tool: https://github.com/BrandEmbassy/php-memory

Then you can just do this: $limitProvider->getLimitInBytes(); and the library converts all valid values for you automatically.

Ivan Kvasnica
  • 776
  • 5
  • 13
-2

Maybe the question is not completely precise. Because the allocation and releasing different memory areas can lead to a patchwork-like memory allocation, the question is probably NOT what you wanted to ask.

For example, you start with 6 megabytes of free RAM, each megabyte of free RAM is denoted by F:

FFFFFF

and allocate three times 1MB, the first one for $a, the second one for $b and the third one for $c then you get this map:

abcFFF

After this, you may release the second megabyte that was allocated for $b, for example, you return from a function in which $b was a local variable. Now the map looks like this:

aFcFFF

Now you have 4 megabytes of free memory, you can allocate 4 times 1 megabyte but you can allocate only 3 megabyte in one chunk.

So, which one is your real question:

  1. What is the largest continuous area I can allocate?
  2. What is the sum of the free area I can allocate?

For the first question, the answer is 3 megabytes, for the second one it is 4.

Csongor Halmai
  • 3,239
  • 29
  • 30