📑 Daftar Isi
- Step 1: Check Your Current Memory Limit
- Step 2: Quick Temporary Fix
- Step 3: Permanent Fix via php.ini
- Step 4: Per-Directory Fix (.htaccess / .user.ini)
- Step 5: WordPress-Specific Optimization
- Step 6: cPanel, Plesk & DirectAdmin Fixes
- Step 7: Find the Real Culprit (Profiling)
- Server-Level Optimization
- Quick Reference: Recommended Memory Limits
- Common Mistakes to Avoid
- FAQ
Look, I get it. You just hit a wall. Your PHP script crashed, and the error message is staring at you: Fatal error: Allowed memory size of X bytes exhausted. It’s frustrating, it’s disruptive, and it always seems to happen at the worst possible time — usually when traffic is spiking or you’re in the middle of a critical batch process.
So here’s the deal: I’ve been dealing with PHP memory limit errors on production servers for years, and I’ve seen every flavor of this problem. From simple WordPress blogs choking on a bloated plugin to enterprise Laravel applications running out of steam during peak hours. The fix is almost always straightforward, but the real value is understanding WHY it happened and making sure it doesn’t happen again. Let me walk you through everything, step by step. No fluff, no theory lectures — just the practical stuff you need.
Step 1: Check Your Current Memory Limit
Before you change anything, figure out what the current limit actually is. Sounds obvious, but you’d be surprised how many people edit the wrong file or assume the limit is something it’s not.
SSH into your server and run this:
php -i | grep memory_limit
You’ll see something like:
memory_limit => 128M => 128M
The first value is the local setting (from ini_set or .user.ini), the second is the global setting from php.ini. If they differ, the local one wins — but only if it’s LOWER than the global. PHP won’t let you raise the limit above what php.ini says through ini_set().
Also grab the path to the active php.ini file:
php --ini | grep "Loaded Configuration File"
This tells you exactly which file you need to edit. Don’t guess — I’ve seen people spend an hour editing /etc/php/8.1/cli/php.ini when the web server uses /etc/php/8.1/fpm/php.ini. Two completely different files. CLI and FPM have separate configs.
Step 2: Quick Temporary Fix
You need the site back up NOW? Here’s the fastest way to buy yourself some time while you figure out the root cause.
Open the PHP file that’s throwing the error and add this at the very top:
<?php
ini_set('memory_limit', '512M');
That’s it. Save the file, refresh the page, and it should work. This is a band-aid, not a cure. You’re telling PHP “hey, give this specific script more room to breathe.” It won’t affect any other scripts on the server.
For WordPress, you can do the same thing in wp-config.php:
define('WP_MEMORY_LIMIT', '512M');
define('WP_MAX_MEMORY_LIMIT', '512M');
Add these lines above the /* That's all, stop editing! */ comment. WP_MEMORY_LIMIT controls the frontend, WP_MAX_MEMORY_LIMIT controls the admin area. The admin area usually needs more because it handles media uploads, imports, and plugin operations.
Important caveat: This temp fix only works if the server’s php.ini allows a limit of at least 512M. If php.ini says 128M and you try ini_set(‘512M’), PHP will silently ignore it and stick with 128M. So if the temp fix doesn’t work, check Step 3.
Step 3: Permanent Fix via php.ini
This is the proper way to fix it for good. Edit the active php.ini file and change the memory_limit directive.
# Backup first (ALWAYS)
cp /etc/php/8.2/fpm/php.ini /etc/php/8.2/fpm/php.ini.bak.20260819
# Edit the file
nano /etc/php/8.2/fpm/php.ini
Find the memory_limit line and change it:
; Before
memory_limit = 128M
; After
memory_limit = 512M
Now restart PHP-FPM so the changes take effect:
# PHP 8.2
systemctl restart php8.2-fpm
# PHP 8.1
systemctl restart php8.1-fpm
# PHP 8.0
systemctl restart php8.0-fpm
# If using Apache mod_php instead of FPM
systemctl restart apache2
Verify the change:
php -r "echo ini_get('memory_limit');"
Should output 512M. If it still shows the old value, double-check you edited the right file. There might be override files in /etc/php/8.2/fpm/conf.d/ that are setting it back.
Step 4: Per-Directory Fix (.htaccess / .user.ini)
Can’t touch php.ini? Maybe you’re on shared hosting or your hosting provider locks it down. No problem — you can override the limit per directory.
For Apache with mod_php or suPHP:
# Add to .htaccess in your website root
php_value memory_limit 512M
For PHP-FPM or LiteSpeed (using .user.ini):
# Create or edit .user.ini in your website root
memory_limit = 512M
A few things to keep in mind:
- .htaccess only works with Apache using mod_php or suPHP. If you’re on PHP-FPM + Nginx, it won’t be read at all.
- .user.ini works with PHP-FPM and LiteSpeed, but LiteSpeed caches it for a few minutes. Either wait or restart LiteSpeed.
- Many shared hosting providers lock memory_limit server-side and won’t allow any override. If your .user.ini change doesn’t take effect, that’s probably why.
Step 5: WordPress-Specific Optimization
WordPress is the #1 culprit for PHP memory limit errors. Between WooCommerce, page builders like Elementor, and a dozen other plugins, memory usage can spiral out of control fast.
Beyond the wp-config.php fix I mentioned in Step 2, here are additional WordPress-specific moves:
Disable memory-hungry plugins one by one. Start with the heaviest ones — page builders, WooCommerce extensions, analytics plugins, and anything that processes large datasets. Disable, test, repeat. If the error stops after disabling a specific plugin, you’ve found your culprit.
Check your theme. Some themes load massive amounts of CSS/JS and run heavy PHP processes on every page load. Switch to a default theme (like Twenty Twenty-Four) temporarily to see if the error goes away.
Optimize WooCommerce specifically. If you run an online store, WooCommerce is likely your biggest memory consumer. Limit the number of products displayed per page, use transients for product data, and consider using a server-side caching plugin like WP Super Cache or LiteSpeed Cache to reduce PHP execution frequency. For deeper WordPress optimization, check our guide on optimizing WordPress on VPS.
Review cron jobs. WordPress runs WP-Cron on every page load by default. If you have heavy scheduled tasks (like WooCommerce stock checks or sitemap generation), they can eat memory on every request. Consider switching to system cron and setting up proper cron scheduling.
Step 6: cPanel, Plesk & DirectAdmin Fixes
If you’re managing a server with a control panel, the fix depends on which one:
cPanel/WHM: Go to WHM → MultiPHP Manager → PHP Selector → Options. Look for memory_limit and change it. If it’s greyed out, your provider has locked it. You can also try editing .htaccess or .user.ini as described in Step 4. Some cPanel setups use /opt/cpanel/ea-phpXX/root/usr/etc/php.ini — check with php --ini to confirm.
Plesk: Go to Tools & Settings → PHP Settings. Change the memory_limit value there. Plesk stores PHP configs per domain, so each website can have different limits. Make sure you’re editing the right domain.
DirectAdmin: Admin Level → Custom HTTPD → look for php_admin_value entries. Or edit the .user.ini in the user’s public_html directory.
If none of these work and your provider has locked everything down, it might be time to consider migrating from shared hosting to a VPS where you have full control.
Step 7: Find the Real Culprit (Profiling)
Okay, here’s where I need you to think differently. Instead of just raising the limit, let’s find out WHY the script needs so much memory in the first place. This is the difference between a band-aid and a real fix.
Quick profiling — add this to your script:
<?php
echo 'Memory at start: ' . number_format(memory_get_usage()) . " bytesn";
// --- Your code goes here ---
// Mark different sections:
echo 'Memory after DB query: ' . number_format(memory_get_usage()) . " bytesn";
echo 'Memory after processing: ' . number_format(memory_get_usage()) . " bytesn";
// At the very end:
echo 'Peak memory usage: ' . number_format(memory_get_peak_usage()) . " bytesn";
Run the script and you’ll see exactly where memory usage spikes. Common patterns I’ve seen:
- Loading all rows at once:
SELECT * FROM orderswith 50,000 rows. Fix: use pagination ormysqli_next_result()to process in chunks. - Building huge arrays: Loop that appends to an array without ever clearing it. Fix: process and discard, or use generators.
- Image processing: Resizing a 4000×3000 photo with GD library can use 100MB+. Fix: reduce dimensions first, then resize.
- String concatenation in loops: Building a 10MB string one character at a time. Fix: use
implode()or write to file incrementally.
For deeper profiling, install Xdebug and enable its profiler. Then analyze the output with KCachegrind or QCachegrind. It’ll show you exactly which functions are eating memory and how long they take.
Server-Level Optimization
Sometimes the problem isn’t one specific script — it’s how your server is configured overall. Here are a few server-level tweaks that can reduce memory pressure across the board:
Enable OPcache. If it’s not already on, you’re leaving performance (and memory savings) on the table. OPcache stores compiled PHP bytecode in shared memory, so each request doesn’t need to re-parse and compile scripts. Add these to your php.ini:
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.enable_file_override=1
Tune PHP-FPM process manager. Each PHP-FPM worker consumes memory. If pm.max_children is too high, you’ll run out of RAM. Quick formula: take your available RAM after OS and MySQL, divide by the average memory per PHP process (check with ps aux | grep php-fpm), and that’s your max_children. For a detailed breakdown of FPM tuning, check our PHP-FPM tuning guide for production servers.
Switch to a more efficient web server. If you’re still on Apache with mod_php, you’re using significantly more memory than necessary. LiteSpeed or Nginx + PHP-FPM are much more memory-efficient. LiteSpeed in particular can reduce memory usage by 30-50% compared to Apache, which directly reduces how often you’ll hit memory limits.
Quick Reference: Recommended Memory Limits
| Site Type | Minimum | Recommended | Notes |
|---|---|---|---|
| Simple WordPress blog | 128M | 256M | Lightweight theme, 5-10 plugins |
| WooCommerce store | 256M | 512M | Payment + shipping + inventory plugins |
| Laravel/Symfony app | 128M | 256M-512M | Depends on queue jobs and query complexity |
| Image processing | 256M | 512M-1G | GD/Imagick are memory-hungry |
| CSV import/export | 256M | 512M-2G | Consider chunked processing |
| WordPress multisite | 256M | 512M | Shared memory across sites |
Common Mistakes to Avoid
Let me save you some pain. Here are the mistakes I see people make over and over:
Mistake 1: Setting memory_limit to -1 (unlimited). Yes, it technically works. No, you should never do it on a production server. One runaway script can consume all available RAM and crash every service. If you need unlimited memory for a CLI script, use php -d memory_limit=-1 script.php instead of changing the global config.
Mistake 2: Editing the wrong php.ini. There are separate configs for CLI and FPM/Apache. Run php --ini to see which one is active for your context. The web server uses FPM, not CLI.
Mistake 3: Forgetting to restart PHP-FPM. You edited php.ini, saved it, refreshed the page, and it still shows the old limit? You forgot to restart. systemctl restart php8.X-fpm and try again.
Mistake 4: Only treating the symptom. If your script needs 2GB of RAM to process a CSV export, the problem isn’t the memory limit — it’s the script. Fix the code, not just the config.
Mistake 5: Not testing before deploying. Always test config changes on staging first. A syntax error in php.ini can take down every PHP site on your server. Always backup, always test.

FAQ
Q: What’s the difference between memory_limit in php.ini vs .user.ini vs .htaccess?
php.ini is the global config that applies to all sites on the server (or per PHP version). .user.ini is per-directory and works with PHP-FPM and LiteSpeed — it overrides php.ini. .htaccess is also per-directory but only works with Apache mod_php/suPHP. The priority order is: .user.ini/.htaccess overrides php.ini. However, some server administrators lock the memory_limit value in php.ini so that no override is possible. If your .user.ini change doesn’t take effect, check for lock directives like memory_limit = 128M in the server config that might be preventing overrides.
Q: Is it safe to set memory_limit to unlimited (-1)?
For production web servers, absolutely not. An unlimited memory limit means any single PHP process can consume all available RAM. If you have a bug or a poorly written script, it can take down your entire server. The only scenario where -1 makes sense is for short-lived CLI scripts (like a one-time data migration) running on a dedicated machine. For web servers, always set a reasonable limit — even 2G is better than unlimited because it at least provides a ceiling.
Q: Why does WooCommerce need so much memory compared to a regular WordPress site?
WooCommerce loads significantly more data than a standard WordPress site. Every product page loads pricing, inventory, tax calculations, shipping options, related products, reviews, and coupon data. Cart operations require session management and stock validation. Order processing involves payment gateway API calls and email notifications. All of this runs in a single PHP request. A simple WordPress blog post might use 30-50MB, while a WooCommerce cart page with 10 products can easily use 150-250MB. Add a few plugins like Subscriptions, Bookings, or Product Add-ons, and you’re looking at 300MB+ per request. That’s why WooCommerce sites need at least 256M and typically run better with 512M.
Q: I keep raising the limit but the error keeps appearing. What now?
If you’ve already raised the limit to 512M or 1G and you’re still hitting it, you almost certainly have a memory leak or an extremely inefficient script. The problem isn’t the limit anymore — it’s the code. Profile your application to find where memory is being consumed. Look for: unbounded database queries loading thousands of rows, recursive functions that don’t have proper exit conditions, growing strings or arrays in loops, or unclosed database connections/cursors. Fix the root cause, not the symptom. In my experience, 90% of “I keep raising the limit” cases turn out to be a single function or plugin that’s consuming 10x more memory than it should.
Here’s my checklist before you call this fixed: 1) Check the actual error log to confirm it’s a memory limit issue, 2) Verify the current memory_limit with php -i, 3) Apply the fix (php.ini, .user.ini, or wp-config.php), 4) Restart the PHP service, 5) Test the fix, 6) Monitor memory usage over the next 24-48 hours to make sure it doesn’t recur. Follow these steps in order and you’ll have this sorted out in minutes, not hours. If you found a faster way or hit an edge case I didn’t cover, drop it in the comments — always looking to learn something new.