PHP can be confusing when it comes to memory allowances. You normally set this value in the php.ini file, but by doing this, you're setting the allowance for each script that anyone runs on any website on that server.
If the value is low such as 16MB then this is fine, but if you have a script that needs a very large amount of RAM such as 512MB or even larger, you don't really want to set the server to this figure because that would mean any script on any site on this server could use this much RAM if it wanted to. Most scripts won't as they'll only use as much as they need (which is generally a small amount) but if you suddenly find yourself with a nasty or accidentally miswritten script that gets stuck in a loop, and is executed by anyone visiting a page, then you can very quickly kill your server by having PHP eat all available RAM.
So how do I allocate more RAM to PHP safely?
Shared hosting providers will not normally let you alter the amount of RAM PHP is allocated, this is for obvious reasons because they don't want a handful of users using the entire pool of RAM to themselves.
But, if you're on your own server or VPS then you can normally override this value in two places.
The first is via a .htaccess
file, simply place the following code into your site's .htaccess file (or create one if it doesn't have one). The htaccess file can be in the website's root (i.e. your httpdocs or webdocs folder) or the folder your script(s) are in, depending on how much of your site you would like it to affect (as htaccess files apply to all content underneath them):
php_value memory_limit 64M
The above code will set the memory limit to 64 megabytes, of course you can set this value to anything you'd like, within reason.
The second method is on a per-script basis
. This is the safest method to use if it is only one or two scripts / pages that need to use considerably more PHP memory than your normal pages. This is done via a single PHP ini_set
that you'll need to drop in at the top of your script:
Again alter 64M to whatever value you need. If the script fails then it'll generally tell you how much more RAM it was trying to grab when it failed so you will have some idea of how much to increase it by.
So there we have it, two much safer methods of giving your scripts and pages more PHP memory when they need that little bit extra. Much better than accidentally breaking your own server when one website goes rogue and eats all your system's RAM.