≡ Menu

How to temporarily set memory limit to unlimited in PHP?

The question – I have a PHP script that I run on the command prompt. As I am parsing very large HTML files, I need to set the memory limit to unlimited for that script only. I do not want to change the global options. How to do that?

PHP scripts have an option to set PHP config variables using the ini_set command. The ini_set command can set any PHP initialization variable to a specific value for that particular script only. This can be used to set the memory_limit variable to an unlimited value (-1).

ini_set('memory_limit', '-1');

Add the above line to the beginning of your PHP script and the PHP interpreter will allow unlimited memory to this particular script! Use this carefully as this might slow down your system if the PHP script starts using an excessive amount of memory, causing a lot of swap space usage.

You can pass in any number here. For example, the following will set the memory limit to 512 mega bytes:

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

Now, check how much memory does php.ini allow:

First, locate your php.ini:

php -i | grep php.ini

This will output:

[root@server ~]# php -i | grep php.ini
Configuration File (php.ini) Path => /etc
Loaded Configuration File => /etc/php.ini

So your php.ini is located at /etc/php.ini.

Now run the following command on your php.ini:

grep -i memory /etc/php.ini

This outputs:

[root@server ~]# grep -i memory /etc/php.ini
; Maximum amount of memory a script may consume (128MB)
; http://www.php.net/manual/en/ini.core.php#ini.memory-limit
memory_limit = 128M

So, by default, PHP will allow 128 mega bytes to each php script run.

Incoming search terms:

  • ini_set kullanımı (1)
  • ini_set memory limit to inifity (1)
  • linux limit unlimted (1)
  • php set memory limit unlimited (1)

Comments on this entry are closed.