Luke
Luke

Reputation: 21286

How to get the memory available to PHP

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?

Upvotes: 6

Views: 12123

Answers (3)

Csongor Halmai
Csongor Halmai

Reputation: 3915

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.

Upvotes: -2

Ivan Kvasnica
Ivan Kvasnica

Reputation: 806

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.

Upvotes: 1

ComFreek
ComFreek

Reputation: 29434

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.

Upvotes: 12

Related Questions