Fatal error out of memory allocated wordpress

I'm getting this nasty error Fatal error: Out of memory (allocated 18087936) (tried to allocate 77824 bytes). Weird thing is, it's 17,25 mb (allocated) and it tried to allocate 76 kb. Memory limit is

I’m getting this nasty error Fatal error: Out of memory (allocated 18087936) (tried to allocate 77824 bytes). Weird thing is, it’s 17,25 mb (allocated) and it tried to allocate 76 kb. Memory limit is 128MB, and as you can see it’s not even close to that. VPS got ~400mb of free ram at that moment. It only happens when I’m posting something and not all the time.
I find it weird and don’t really know what can cause it.
Let me know if you need any additional info.

asked Apr 13, 2013 at 20:45

Igor Yavych's user avatar

9

The error says that the memory limit is 18M and not 128M. This means that somewhere the memory_limit is set to something different than 128M (local php.ini, or the application itself, since PHP can override this setting at run-time).

I would suggest that you first create a file called (say) phpinfo.php with the following contents:

<?php
phpinfo();
?>

and place it where your script runs. Then access the file with your browser and look for the actual memory_limit value. If it’s still showing 128M both for «global» and «local» value, then probably somewhere in your code, there’s a «ini_set(«memory_limit», $value);» call or something similar. Otherwise, if it says 18M, look for other places where this can be set:

  • Check your wp-config.php file
  • Check for any local php.ini file (look into the phpinfo.php page to see the location of the actual loaded php.ini file)
  • Check for any .htaccess files that contain such a directive

answered Apr 14, 2013 at 12:08

periklis's user avatar

periklisperiklis

10k6 gold badges61 silver badges66 bronze badges

7

Hope this helps, as I had the same issue:

You’re running into a limitation in WordPress’s own memory limit, not your PHP memory_limit. WordPress implemented this limit in order to prevent poorly written scripts from shutting down your whole PHP interpreter. Unfortunately, as you’ve noticed, it’s rather barebones.

The easiest way I’ve found to fix this is to install the Change Memory Limit plugin from WordPress plugin repository. It allows you to fix the issue without modifying any WP files manually.

The 64M default for the plugin will probably be fine for you.

Alternatively, if you don’t want to trust a third party plugin, add the following line to wp-config.php:

define('WP_MEMORY_LIMIT', '64M');

answered Apr 22, 2013 at 10:05

Glitch Desire's user avatar

Glitch DesireGlitch Desire

14.4k7 gold badges41 silver badges55 bronze badges

4

Got it from this http://wordpress.org/support/topic/fatal-error-out-of-memory-messages?replies=24#post-1929111, thought I’d share it with you guys :


THIS TO BE ENTERED IN THE WP-CONFIG FILE WHICH IS IN THE ROOT OF THE WORDPRESS SETUP:
ENTER AFTER : 
define('ABSPATH', dirname(__FILE__).'/');
THE FOLLOWING:

define('WP_MEMORY_LIMIT', '64M');

ALSO CREATE A PHP.INI WHICH SHOULD BE UPLOADED TO THE PLUGIN FOLDER IN WP-CONTENT:

 `memory_limit = 128M; //Maximum amount of memory a script may consume (64MB)
`

max_execution_time = 45;


upload_max_filesize = 15M;


post_max_size = 30M;

Hope this helps!

answered Apr 22, 2013 at 10:06

Hiren Pandya's user avatar

Hiren PandyaHiren Pandya

9791 gold badge7 silver badges20 bronze badges

Just an option that helped me debugging these errors.

If you have access to the .htaccess, you could try this:

php_value upload_max_filesize 128M
php_value post_max_size 128M
php_value max_execution_time 300
php_value max_input_time 300

If that doesn’t help, you could try this to check the settings:

echo 'Max upload size: ' . ini_get('upload_max_filesize') . '<br />';
echo 'Max post size: ' . ini_get('post_max_size') . '<br />';
echo 'Memory limit: ' . ini_get('memory_limit');

I hope this works, for me it did.

answered Apr 16, 2013 at 14:49

Ron van der Heijden's user avatar

I am not sure this causes the error, but it is worth checking for.

Many of the most untraceable pathetic out of memory errors are caused by :

1) User defined exception handlers, causing exceptions therefore recursing.

2) The above + trying to fetch class information of object originating the exception, and the class information testing causes an autoload attempt, in which autoload throws another exception and therefore recursing.

Have you done something conflicting with WP error handling or autoload?

answered Apr 17, 2013 at 12:15

Volkan's user avatar

VolkanVolkan

2,2121 gold badge14 silver badges14 bronze badges

I install wp-memory-usage plugin by alexrabe on all my WordPress sites.

This plugin helps you to see what WordPress is seeing in terms of your PHP memory usage. Other approaches may show you the PHP settings at the server, however these settings are often overridden with various techniques the closer you get to a rendered page within the browser.

To set your max memory -> open your favorite text editor and create a file called php.ini; include in the file the following line:

memory_limit = 256M

Place a copy of the php.ini your WordPress root directory. I also place copies in: /wp-admin; /wp-content; and /wp-includes.

answered Apr 18, 2013 at 13:59

TECH N's user avatar

Add define('WP_MEMORY_LIMIT', '256M'); in your wp-config.php file. Its the easiest way.

answered Apr 20, 2013 at 13:26

aakash's user avatar

aakashaakash

3761 gold badge5 silver badges18 bronze badges

1

It looks as through somewhere in the site, the memory limit is being overwritten, do a site wide search in the code for ini_set('memory_limit' and see what is returned.

answered Apr 21, 2013 at 3:12

duellsy's user avatar

duellsyduellsy

8,3972 gold badges35 silver badges60 bronze badges

1

Given that your phpinfo() script returns the correct value for memory usage, this is obviously being set in WordPress somewhere, and is therefore overriding the Apache provided values, so using a .htaccess to apply this still won’t work.
This link (http://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP) suggests that WordPress does its own memory management by default, so setting the (‘WP_MEMORY_LIMIT’, ‘256M’) in the wp-config.php is logical.

If you have shell access to the server hosting your site I would suggest going to the DocumentRoot of your wordpress install and running the following commands:

grep -R "18M" *
grep -R -e '(WP_MAX_MEMORY_LIMIT|WP_MEMORY_LIMIT)' *

This will search through your files for the string 18M (the value your memory limit seems to be set to in human readable terms) and the configuration options for the WordPress defined memory limit. I suspect that one of these commands will return positive output. You should then change the WP_MEMORY_LIMIT as suggested (although 256M may be a little high — try 64M initially, you don’t want to cause yourself potential problems).

answered Apr 22, 2013 at 9:59

Chris's user avatar

ChrisChris

465 bronze badges

4

В произвольный момент времени любой разработчик, создающий тему или плагин, либо просто пользователь, работающий с 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, ведь люди не стараются понять проблему.

Да, у нас под рукой всегда имеются материалы, которые прекрасно спасают в беде. Однако стоит помнить, что понимание проблемы помогает нам расширить свой багаж опыта, развивать и совершенствовать свой уровень.

В данной ситуации очень полезно разобраться с тем, почему возникла такая ошибка.

Содержание

  1. Ошибка нехватки памяти в WordPress
  2. Переводим байты в мегабайты
  3. Настройка PHP
  4. Увеличиваем лимит памяти
  5. Несколько слов о выделении памяти

Ошибка нехватки памяти в WordPress

Используя приведенное выше сообщение, мы можем сказать, что выделенный объем памяти составляет 268435456 байт. Однако кто сейчас считает в байтах?

Нам гораздо удобнее оперировать мегабайтами, гигабайтами и терабайтами (хотя если у вас такой объем памяти, и вы столкнулись с указанной ошибкой, то это – совсем другая история).

Переводим байты в мегабайты

Первое, что мы сделаем – это переведем байты в мегабайты. Сделать это можно, к примеру, с помощью Google — достаточно ввести в поисковую строку следующий текст:

268435456 bytes to megabytes

В итоге мы получим результат:

bytes_to_mb

Очень удобно. Но что нам делать с этой информацией?

Во-первых, мы должны понимать, что у нас есть предел в 256 Mb памяти, которая доступна для использования в WordPress и PHP, и этой памяти не хватает для совершения операций.

Честно говоря, ограничения нужно выставлять для PHP, однако я буду работать с WordPress, поскольку часть решения проблемы может включать в себя определение новой константы. Однако об этом – через одно мгновение.

Настройка PHP

Нужно понимать то, что PHP имеет лимит памяти, а также то, что вы можете в некотором роде управлять им через WordPress. Обычно есть две вещи, которые нужно сделать, чтобы убедиться в том, что проблема решена в полном объеме.

Но сначала надо узнать, какую именно версию PHP вы используете. Если вы работаете с PHP на локальной машине, то вы, скорее всего, сможете найти версию PHP в панели управления своего веб-сервера:

php_adjust

В противном случае версия должна отображаться где-либо в пределах панели управления вашего хостинг-аккаунта.

Это даст нам понять, какой конфигурационный файл PHP нужно редактировать. В частности, вам нужно найти файл php.ini, который связан с вашей версией PHP.

Если у вас установлена только одна версия, прекрасно; иначе вам нужно будет найти файл php.ini для вашей определенной версии PHP, которая в данный момент запущена.

Увеличиваем лимит памяти

Как только вы найдете файл php.ini, взгляните на директиву memory_limit.

php_memory

На скриншоте выше можно видеть, что лимит памяти установлен в 25 Mb, что явно меньше требуемого нам. Потому нам понадобится увеличить его до, скажем, 128 Mb, после чего перезапустить сервер.

Что делать, если WordPress по-прежнему жалуется на ошибку?

В данном случае вам, возможно, понадобится внести одно дополнительное изменение в файл wp-config.php. Есть две константы, которые мы можем определить:

  1. WP_MEMORY_LIMIT
  2. 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 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

JSS's user avatar

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

Milo's user avatar

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

Damien's user avatar

DamienDamien

2,2112 gold badges13 silver badges25 bronze badges

2

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!!!

TPC Memory Report
This report shows my memory usage before and after upgrading to PHP5.4. The difference 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

Brian Shim

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.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error opening dependency file dep main o d no such file or directory
  • Fatal error online session interface missing please make sure steam is running
  • Fatal error onewire h no such file or directory
  • Fatal error one or more table pointers are invalid modification could be unsafe
  • Fatal error u1073

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии