В произвольный момент времени любой разработчик, создающий тему или плагин, либо просто пользователь, работающий с WordPress, может столкнуться с ошибкой Fatal Error: Memory Exhausted (память исчерпана). Обычно эта ошибка выглядит следующим образом:
Fatal error: Allowed memory size is 268435456 bytes exhausted (tried to allocated 29596635 bytes) in …/wp-includes/wp-db.php on line 885.
Безусловно, ваше сообщение об ошибке может иметь несколько иной вид, однако смысл его одинаков: вы столкнулись с ошибкой, она имеет отношение к доступному объему памяти, вы знаете, какой именно объем памяти был затребован, а также какой файл вызвал ошибку.
По моему мнению, одна из самых заметных проблем с такими вот ошибками – это слишком быстрое нахождение решения в Google, ведь люди не стараются понять проблему.
Да, у нас под рукой всегда имеются материалы, которые прекрасно спасают в беде. Однако стоит помнить, что понимание проблемы помогает нам расширить свой багаж опыта, развивать и совершенствовать свой уровень.
В данной ситуации очень полезно разобраться с тем, почему возникла такая ошибка.
Содержание
- Ошибка нехватки памяти в WordPress
- Переводим байты в мегабайты
- Настройка PHP
- Увеличиваем лимит памяти
- Несколько слов о выделении памяти
Ошибка нехватки памяти в WordPress
Используя приведенное выше сообщение, мы можем сказать, что выделенный объем памяти составляет 268435456 байт. Однако кто сейчас считает в байтах?
Нам гораздо удобнее оперировать мегабайтами, гигабайтами и терабайтами (хотя если у вас такой объем памяти, и вы столкнулись с указанной ошибкой, то это – совсем другая история).
Переводим байты в мегабайты
Первое, что мы сделаем – это переведем байты в мегабайты. Сделать это можно, к примеру, с помощью Google — достаточно ввести в поисковую строку следующий текст:
268435456 bytes to megabytes
В итоге мы получим результат:
Очень удобно. Но что нам делать с этой информацией?
Во-первых, мы должны понимать, что у нас есть предел в 256 Mb памяти, которая доступна для использования в WordPress и PHP, и этой памяти не хватает для совершения операций.
Честно говоря, ограничения нужно выставлять для PHP, однако я буду работать с WordPress, поскольку часть решения проблемы может включать в себя определение новой константы. Однако об этом – через одно мгновение.
Настройка PHP
Нужно понимать то, что PHP имеет лимит памяти, а также то, что вы можете в некотором роде управлять им через WordPress. Обычно есть две вещи, которые нужно сделать, чтобы убедиться в том, что проблема решена в полном объеме.
Но сначала надо узнать, какую именно версию PHP вы используете. Если вы работаете с PHP на локальной машине, то вы, скорее всего, сможете найти версию PHP в панели управления своего веб-сервера:
В противном случае версия должна отображаться где-либо в пределах панели управления вашего хостинг-аккаунта.
Это даст нам понять, какой конфигурационный файл PHP нужно редактировать. В частности, вам нужно найти файл php.ini, который связан с вашей версией PHP.
Если у вас установлена только одна версия, прекрасно; иначе вам нужно будет найти файл php.ini для вашей определенной версии PHP, которая в данный момент запущена.
Увеличиваем лимит памяти
Как только вы найдете файл php.ini, взгляните на директиву memory_limit.
На скриншоте выше можно видеть, что лимит памяти установлен в 25 Mb, что явно меньше требуемого нам. Потому нам понадобится увеличить его до, скажем, 128 Mb, после чего перезапустить сервер.
Что делать, если WordPress по-прежнему жалуется на ошибку?
В данном случае вам, возможно, понадобится внести одно дополнительное изменение в файл wp-config.php. Есть две константы, которые мы можем определить:
- WP_MEMORY_LIMIT
- WP_MAX_MEMORY_LIMIT
Узнать подробнее про них можно в кодексе. Как показывает мой опыт, удобнее всего определить сразу две константы, чем одну WP_MEMORY_LIMIT.
Я упомянул это, потому что в сети ходят советы, согласно которым можно просто задать WP_MEMORY_LIMIT. Я не говорю, что это неправильно – просто у меня были наилучшие результаты, когда были определены обе константы.
По аналогии с php.ini, добавляем в wp-config.php следующие значения:
define('WP_MEMORY_LIMIT', '128M');
define('WP_MAX_MEMORY_LIMIT', '128M');
Это должно решить проблему.
Также можно задать следующее правило в .htaccess:
php_value memory_limit 256M
Несколько слов о выделении памяти
Хочу сказать еще пару слов о выделении памяти. Несмотря на то, что самое простое решение – это увеличить доступную память, его не обязательно нужно делать в самом начале.
Фактически, я прибегаю к нему уже под конец, когда ничего не помогает.
Зачастую эта проблема является результатом работы какого-либо фрагмента кода, процедуры или определенного алгоритма – все это можно усовершенствовать и оптимизировать.
Таким образом, обязательно проверьте ваш код – используйте различные инструменты отладки и тестирования, чтобы исключить неэффективные участки. Если таковых нет, то тогда уже можно прибегать к корректировке памяти.
Источник: tommcfarlin.com
I have set php memory limit from whm to 256M from WHM > PHP Configuration Editor.
Even so, my wordpress website and admin is showing me an error like below.
Fatal error: Out of memory (allocated 36175872) (tried to allocate 30720 bytes) in /home/XXXX/public_html/wp-includes/class-simplepie.php on line 14272
Fatal error: Out of memory (allocated 35127296) (tried to allocate 1966080 bytes) in /home/XXXX/public_html/wp-includes/class-simplepie.php on line 5427
I also tried to add following line to the top of wp-config.php, but no luck and same error.
define('WP_MEMORY_LIMIT', '128M');
can anyone suggest me or tell me what may be the solution?
hakre
189k51 gold badges426 silver badges824 bronze badges
asked Jul 31, 2011 at 5:48
3
I finally think I’ve solved the White Screen of Death from PHP out of memory Fatal Errors.
Full details here: http://www.isthisyourhomework.com/how-to-fix-the-wordpress-white-screen-of-death/
If setting the WordPress and PHP memory limits doesn’t work for you, try adding/edditing the following line in either your Apache conf files. I didn’t have access to those, so I added the following line to the .htaccess file in my WP server’s document root:
RLimitMEM max
Many hosts have set limits on each user on shared-use servers. The above setting will unfetter your server and banish the WSOD.
answered Oct 12, 2012 at 1:36
MrTempleMrTemple
711 silver badge2 bronze badges
1
The SimplePie people reckon that this is caused by a bug in PHP. It was fixed in PHP version 5.3. Upgrading might help.
Newer versions of SimplePie use less memory but still suffer from the same PHP bug that causes lots of cached items to cause you to use loads of memory.
answered Nov 17, 2011 at 18:21
LadadadadaLadadadada
5103 silver badges15 bronze badges
Did you change the memory limit in php.ini(or through WHM service configuration page)? If so, try rebooting Apache
answered Jul 31, 2011 at 6:09
1
i have a memory issue while NextgenGallery try to create the thumbnails.
Wp-Version is 3.4.1
Fatal error: Out of memory (allocated 29884416) (tried to allocate 2000 bytes) in
/xxx/wp-content/plugins/nextgen-gallery/lib/gd.thumbnail.inc.php
on line 179
But my memory is not exceeded:
PHP Version : 5.2.17 / 32Bit OS
Memory limit : 128 MByte
Memory usage : 27.75 MByte
I am getting desperate trying to solve this issue.
Many thanks in advance for any help,
Joe
asked Jul 16, 2012 at 13:22
I’m not sure where you’re getting those stats, but I doubt that is showing you the amount of memory being used while processing the images. If you navigate to some memory use screen, you’re seeing the amount of memory currently allocated, which is now an entirely different process from when you were uploading images. The fact that Out of memory (allocated 29884416) is already larger than 27.75 MByte points to this.
answered Jul 16, 2012 at 14:02
MiloMilo
77.2k3 gold badges116 silver badges160 bronze badges
1
this just means you need to make a small change in your .htaccess or create a php.ini to increase the allocated memory for WordPress.
You and your visitors will see this out of memory error when WordPress is trying to process something (in your case the thumbnails).
Try either of these to fix the problem
1. Create a file in your root /WordPress folder called php.ini , add this line in PHP.ini
memory_limit = 64M;
2. If you don’t have access to PHP.ini try adding this to an .htaccess file:
php_value memory_limit 64M
You can also try increasing it to 128M or 256M
If that doesn’t work — contact your web host provider for their preferred method.
answered Aug 18, 2012 at 9:10
DamienDamien
2,2112 gold badges13 silver badges25 bronze badges
2
facing a PHP Fatal Error: Out of memory error in your WordPress website ? This is one of the most common errors in WordPress, which you can easily fix it by increasing the Php memory limit in WordPress setup website. In today article, we will show you how to fix Fatal error: Out of memory error in worpdress.
Increase PHP Memory Limit in WordPress to Fix Fatal error: Out of memory worpdress
To increase memory limit in WordPress site need to edit the wp-config.php file which is located in WordPress site’s root folder, with use of FTP access or CPanel > File Manager you able to easily reach at WordPress setup root directory and find wp-config.php file which you need to edit for Fix Fatal Error: WordPress Memory Exhausted Error by Increase PHP Memory.
Next, Add following WP_MEMORY_LIMIT line in wp-config.php file just before the line that says ‘That’s all, stop editing! Happy blogging.’
// increase memory limit in WordPress define( 'WP_MEMORY_LIMIT', '512M' ); // change 512M according need
Above code tells WordPress to use memory limit ‘512M’ instead of default memory limit avail in WordPress setup server and this way we able to increased the PHP memory limit and fix Fatal error: Out of memory worpdress / WordPress Memory Exhausted Error
If you getting errors while working in the wp-admin area of WordPress, try adding the WP_MAX_MEMORY_LIMIT code beneath the memory limit code,
like so:
// increase memory limit in WordPress
define('WP_MEMORY_LIMIT', '512M' ); // change 512M according need
define('WP_MAX_MEMORY_LIMIT', '128M');
Basically:
WP_MEMORY_LIMIT = WordPress front end
WP_MAX_MEMORY_LIMIT = WordPress back end
Make sure, for safety you taken original file backup before edit wp-config.php and uploaded / Save edited wp-config.php in WordPress setup Root directory. in case it anything wrong happen than upload back your backup file and contact our Experience WordPress Developer who ready to help in solve Fatal Error: WordPress Memory Exhausted Error in free of cost 🙂
After increased Memory limit with edit wp-config.php now visit your WordPress site and memory exhausted error should disappear now.
Important Note: If given above solution not work for you, then it means your hosting service provider not allow to increase PHP memory limit by editing wp-config.php file. and you need to contact your web hosting support team and request them to increase PHP memory limit manually for your WordPress hosting account.
If you Fixed WordPress Memory Exhausted Error by Increase PHP Memory in any other way please share in comment.
Enjoy Life 🙂
Have you ever gotten this Linux “out of memory” error when working with your WordPress site?
Fatal error: Out of memory (allocated 63963136) (tried to allocate 7864320 bytes) in [path]/wp-content/plugins/wordfence/lib/wfBrowscapCache.php.php on line 16388
If you Google around to solve this problem, almost all of the advice you’ll get is to increase your PHP and WordPress memory limits, or add memory to your server, or to remove plugins.
I didn’t want to just increase memory. I wanted to solve the root cause of the problem. The site was running on an Amazon EC2 small instance with Amazon AMI. It should not be running out of memory!
If you want to go directly to my results, jump ahead to my recommendations. Otherwise, here’s my story:
How I Investigated This Problem
When I first got this error, I installed the TPC! Memory Usage Plugin on my live site. [Note: I no longer recommend that plugin since it’s not maintained. Use Server IP & Memory Usage Display instead.]
I installed this plugin on my local development site as well and was totally blown away when I compared the memory usage on my local site vs. live site: the same site with the same plugins was using 34.13MB on my local server and 60.0MB on the live site. WOW!!!
How could this be? There must have been something in the server setup that caused the discrepancy. Googling some more, I read that PHP5.4 uses significantly less memory than PHP5.3, by a huge amount, on the order of cutting it in half. Sure enough, I checked and found out that my local server was running PHP5.4 while my live server was running PHP5.3. It seemed like a smoking gun, but I needed to do one more experiment to be sure.
I had another WordPress site running on Amazon EC2 with Amazon AMI, running PHP5.3. Memory usage for that was 47.8MB. After I upgraded that server to PHP5.4, it used 30.0MB. It was clear, switching from PHP5.3 to PHP5.4 saved almost 18MB of memory! That is huge!!!

My Number One Recommendation – Upgrade PHP
Based on these findings, my number one suggestion to reduce WordPress memory usage is to upgrade from PHP 5.x on your server to PHP 7.x, which is even faster and more memory-efficient. I’m now using PHP 7.3 on all of my personal and client sites.
If you are on shared hosting like GoDaddy, 1&1, Dreamhost, etc., there is often a button in the control panel to upgrade. Simple as that.
If you are running your own Linux server, it’s more complicated. Here is an article describing what I did to upgrade from PHP5.3 to PHP5.4 on Amazon AMI. (This procedure also works for upgrading to PHP5.5 and beyond). Note that there are other solutions to reducing PHP memory usage like Xcache. I’m considering that to be an advanced solution beyond the scope of this article. If you want to try that, go for it and let me know how it goes in the comments!
Be sure to re-test your site and plugins after you upgrade, as there might be some old code not compatible with PHP 7.x. I have not encountered problems with PHP 7.3 on my WordPress sites.
This Can Also Fix HTTP ERROR 500
On a different site, I was getting HTTP ERROR 500 when I tried to edit a page. Viewing pages on the front end was fine. I suspected some sort of memory issue. After trying a bunch of other stuff, I simply upgraded PHP from 7.0 to 7.1 and it solved the problem!
And Don’t Forget..
Of course, it also helps to delete unused plugins. If you want, you can install the Server IP & Memory Usage Display plugin and deactivate plugins on at a time to see their contribution to your memory usage. (Just remember to deactivate it when you’re done, because it contributes to memory usage as well). I can almost guarantee you that none will save you 18MB like switching to PHP5.5 or greater might do! But, eliminating plugins might be just enough to stop your memory errors from happening.
If you are not able to upgrade to PHP7+, and you can’t delete any more plugins, then you can always increase your allowable memory usage and/or get more memory for your server like the vast majority of articles recommend. The Server IP & Memory Usage Display plugin will tell you how much memory is allocated to WordPress (usually 40MB) and to PHP (usually 64MB or 128MB). You can Google around to see how to increase these limits.
But, I prefer to solve the root cause of the problem rather than treat the symptoms!
I hope my experience was helpful to you. Please comment on your findings and experiences about WordPress memory usage! – Brian
I am a freelance web developer and consultant based in Santa Monica, CA who uses WordPress, PHP, and JavaScript to create websites and web applications for businesses, nonprofits, and organizations.





