How to get the memory available to PHP

Viewed 9508

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?

3 Answers

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.

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.

Related