Skip to content
Hosting Operations8 min read

PHP Memory Limit Exhausted Fix: 7 Methods Compared

Fix PHP memory exhausted errors fast. Compare ini_set, .htaccess, php.ini, and WP-CLI methods with trade-offs for shared hosting and VPS.

Written by Abdul AbrorTechnical Hosting Support Engineer
Close-up of a black pci-e power cable connector.
On this page

TL;DR — Key takeaways

  • php.ini changes apply server-wide and survive reboots, but require root access or control panel support
  • .htaccess and .user.ini work on shared hosting without root but may be overridden by hosting policies
  • Runtime ini_set fixes are temporary per-request and best for one-off scripts or emergency patches
  • WordPress needs both PHP and WP_MEMORY_LIMIT raised; check which limit is actually blocking execution
  • Monitor real usage with memory_get_peak_usage before blindly raising limits to avoid masking code problems

The "Allowed memory size of X bytes exhausted" error stops your PHP scripts cold. I've seen this kill checkout pages, break imports, and trigger 3 AM support tickets more than any other PHP issue.

Seven methods exist to raise the memory_limit directive. Each has different scope, persistence, and permission requirements. This comparison walks through the trade-offs so you pick the right fix for your hosting environment and use case.

Understanding PHP Memory Limits and Why They Exist

PHP enforces memory_limit to prevent runaway scripts from consuming all available RAM and crashing the server. The default is often 128M, which handles most small applications fine.

Problems surface when you process large files, run image manipulation, handle big database result sets, or use memory-hungry frameworks and plugins. The error message tells you exactly how many bytes the script tried to allocate and where it failed.

Check your current limit first. Run php -i | grep memory_limit on the command line or create a phpinfo.php file with <?php phpinfo(); ?> and search for memory_limit in the output. Knowing the starting point matters before you change anything.

Method Comparison Table

Here are the seven methods side by side. Scope determines where the change applies, persistence tells you if it survives a reboot, and access level shows what permissions you need.

  • php.ini edit: Server-wide scope, permanent, requires root or control panel access
  • .htaccess with php_value: Directory and subdirectories, permanent, works on Apache with mod_php only
  • .user.ini with memory_limit: Directory and subdirectories, permanent, works on PHP-FPM and CGI
  • ini_set in PHP code: Single script execution, temporary per request, no special access needed
  • WP_MEMORY_LIMIT in wp-config.php: WordPress admin only, permanent for WP, file edit access required
  • PHP-FPM pool configuration: Per-pool scope, permanent, requires root access to FPM config
  • Control panel interface: Varies by host, permanent, easiest option when available

Shared Hosting: .htaccess and .user.ini Methods

Most shared hosting blocks php.ini access and disables ini_set. Your two options are .htaccess or .user.ini depending on how PHP runs.

For Apache with mod_php, create or edit .htaccess in your web root and add php_value memory_limit 256M on its own line. Save and test immediately. If you get a 500 error, your host disabled php_value directives and you need to contact support.

.user.ini works when PHP runs as CGI or FPM. Create a file named .user.ini in your web root with memory_limit = 256M and save it. Changes may take up to five minutes because PHP caches .user.ini with the user_ini.cache_ttl setting.

Both methods apply to the directory where you placed the file and all subdirectories. That means one .htaccess or .user.ini at the root covers your entire site.

VPS and Dedicated Servers: php.ini and PHP-FPM Pool Edits

With root access you control the master php.ini file. Find it with php --ini which lists the loaded configuration file path. Common locations are /etc/php/8.2/fpm/php.ini or /etc/php.ini.

Open the file, search for memory_limit, change the value to 512M or whatever you need, save, and restart the web server or PHP-FPM. For Apache run systemctl restart apache2 or httpd. For PHP-FPM run systemctl restart php8.2-fpm substituting your actual PHP version.

PHP-FPM users can set per-pool limits instead of server-wide. Edit /etc/php/8.2/fpm/pool.d/www.conf and add php_admin_value[memory_limit] = 512M in the pool block. This overrides php.ini for that specific pool and is harder to accidentally change later.

Both approaches persist across reboots and apply immediately after the service restarts. I prefer the FPM pool method when I run multiple sites because it isolates limits per application.

Runtime Fixes with ini_set: When and Why

Calling ini_set('memory_limit', '512M'); at the top of your PHP script raises the limit for that one execution only. The next request starts fresh with the server default.

This works for one-off import scripts, CLI maintenance tasks, or emergency patches when you can't wait for a server restart. It does nothing if your hosting provider compiled PHP with suhosin or disabled ini_set in the master php.ini.

Test if ini_set is allowed by running ini_set('memory_limit', '256M'); echo ini_get('memory_limit'); in a test script. If it still shows the old value, the function is disabled.

WordPress-Specific Configuration

WordPress checks two limits: the PHP memory_limit and its own WP_MEMORY_LIMIT constant. The PHP limit is the hard ceiling. WP_MEMORY_LIMIT sets a lower artificial cap for the admin area unless you also define WP_MAX_MEMORY_LIMIT.

Open wp-config.php and add these lines right after the database constants and before the "stop editing" comment:

define('WP_MEMORY_LIMIT', '256M'); define('WP_MAX_MEMORY_LIMIT', '512M');

WP_MEMORY_LIMIT applies to the front end. WP_MAX_MEMORY_LIMIT applies to the admin and affects plugin installations, theme updates, and image processing. If you raise WP_MAX_MEMORY_LIMIT above the PHP memory_limit, PHP still wins and the script dies.

After editing wp-config.php, log into the admin and go to Site Health under Tools. The info tab shows both limits. Mismatched values there tell you which limit is actually blocking execution.

Testing and Validation

Never assume the change worked. Verify it. Run php -r "echo ini_get('memory_limit');" from the command line or access your phpinfo.php page and search for the memory_limit row.

For WordPress, install the Query Monitor plugin temporarily and check the Environment panel. It shows both PHP and WordPress memory limits and current usage. Remove the plugin after confirming the fix.

Load the page or script that originally failed and watch the error log. On Linux check /var/log/apache2/error.log or /var/log/php-fpm/error.log. Tail the log in real time with tail -f /var/log/php-fpm/error.log while you reproduce the issue.

Check actual memory usage with memory_get_peak_usage(true) at the end of your script. If the script uses 180M and you set the limit to 256M, you have headroom. If it uses 510M out of 512M, the real problem is probably inefficient code and you should profile it before raising limits further.

Trade-offs and Recommendations

php.ini edits are permanent and apply everywhere but require root access and service restarts. Use this for VPS or dedicated servers where you control the environment.

.htaccess and .user.ini work on shared hosting but may be overridden by hosting policies or server-level restrictions. Try these first if you lack root access.

ini_set is fast for testing and temporary fixes but does not persist. Use it for one-off scripts, emergency patches, or when you want to isolate a memory bump to a specific operation.

WordPress needs both PHP and WP limits raised. Set WP_MEMORY_LIMIT to match your PHP limit and WP_MAX_MEMORY_LIMIT slightly higher if admin operations fail. Always test in staging first because raising limits sometimes exposes secondary bugs in poorly written plugins.

Control panel interfaces like cPanel or Plesk are the safest choice when available because they validate the change and restart services automatically. Check your hosting dashboard before editing files manually.

When Raising Limits Is Not the Answer

If you routinely hit 512M or 1G memory limits, the script has a design problem. Profile it. Install Xdebug or Blackfire and trace where memory accumulates.

Common memory hogs include loading entire database tables into arrays, processing images without destroying resources, recursive functions without limits, and caching every query result in memory. Fix the code instead of masking it with higher limits.

In support tickets I handled, the usual culprit was a plugin loading 50,000 posts into memory to build a dropdown menu. The fix was pagination or a lightweight query, not a 2G memory limit.

Quick troubleshooting checklist

  • Identify current memory_limit value with php -i | grep memory_limit or phpinfo()
  • Check actual script usage with memory_get_peak_usage(true) to right-size the new limit
  • Test the fix in a staging environment or low-traffic window first
  • Verify the change took effect by running phpinfo() or php -r "echo ini_get('memory_limit');"
  • Monitor error logs for 24 hours after applying the fix
  • Document which method you used and where the configuration file lives
  • Set up a reminder to review memory usage monthly and optimize heavy scripts

FAQ

Why does increasing memory_limit in code not work on my shared host?

Many shared hosting providers lock memory_limit changes at the server level with the PHP suhosin extension or by disabling ini_set in php.ini. Contact your host to confirm if runtime changes are allowed or if you need to request a limit increase through their control panel.

What is a safe memory_limit value for a WordPress site?

Start with 256M for typical WordPress sites. WooCommerce or page builders often need 512M. If you hit limits above 512M regularly, profile your plugins and queries first because the root problem is usually inefficient code, not insufficient memory.

Do I need to restart Apache or PHP-FPM after changing php.ini?

Yes for php.ini changes. Apache with mod_php needs a full Apache restart. PHP-FPM needs a service restart with systemctl restart php-fpm or php8.2-fpm depending on your version. .htaccess and .user.ini changes usually take effect immediately without a restart.