php fatal error allowed memory size of 2097152 bytes exhausted

Ошибка — Fatal error: Allowed memory size

Ошибка Fatal error: Allowed memory size гласит о том, что вы достигли ограничения по памяти, которые у вас установлены в настройках web-сервера.

Например, текст ошибки:

Решение проблемы с ограничением памяти

Есть два варианта как завершить операцию:

Увеличить лимит по памяти.

Первый вариант сложен и не всегда возможен. Поэтому рассматривать его не будем.

Хотя, зачастую бывает так, что сайт, например, пытается сжать очень большую картинку в другой размер (например, фото в оригинале весит 20 Мб). В этом случае просто используйте оригинальные картинки меньшего размера.

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

Файл php.ini

Это рекомендуемый способ, если вы имеете доступ к файлу php.ini. Данный способ не сработает на многих платных хостингах провайдер, т.к. там закрывают доступ к этому файлу, в целях безопасности. Внимание! Данный способ затронет все ваши сайты и скрипты, находящиеся на сервере.

Откройте файл php.ini и найдите там строку memory_limit:

Добавьте в самом начале строку php_value memory_limit 256M. Во время выполнения PHP, запишите перед тяжелыми операциями в php-файл следующую строчку

Как посмотреть, сработало ли?

Откройте в панели управления Joomla информацию о системе

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

И найдите строку memory_limit

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

Если не получилось.

В случае, если рекомендации из статьи не помогли вам (возможно хостинг не дает таких прав), то обратитесь с этим вопросом к техподдержке вашего хостинга. Если хостер отказал, то рассмотрите вариант с выполнением тяжелых операций на локальной машине. Затем результат работы перенесите на ваш продуктивный сайт в интернете.

Альтернатива

Также оптимизации по памяти можно добиться установкой APC. Он уменьшает потребление памяти в

1,5-2 раза и ускоряет работу всего сайта в целом. Для нормальной работы Joomla + JBZoo обычно хватает 64 Мб (с серьезным запасом на будущее).

Источник

Ошибка Fatal error: Allowed memory size

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

На приведенном примере видно, что движок PHP при обработке данной страницы попытался использовать память свыше установленного лимита в 256 мегабайт (268435456 байт). Откуда же взялся этот лимит, почему он превышен и как избавиться от подобных ошибок?

Почему это происходит?

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

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

Если даже сайт работает без каких-либо проблем в течение долгого времени, при выполнении определенных ресурсоемких операций (обработка крупных графических изображений или импорт большого числа товаров в интернет-магазин из файла-каталога) также может возникнуть подобная ошибка.

Как исправить ошибку “Fatal error: Allowed memory size”?

Многие хостинг-провайдеры разрешают пользователю изменять настройки PHP с помощью файлов конфигурации. И тем более изменение настроек необходимо, если используется собственный виртуальный сервер VDS.

Прежде всего следует уточнить действующие лимиты для PHP. Для этого можно создать на хостинге в каталоге с сайтом файл info.php следующего содержания (см. ниже) и открыть его в браузере.

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

Функция “phpinfo();“ заставит движок PHP сгенерировать страницу с подробным отчетом о всех настройках, лимитах и подключенных модулях. Находим на странице строку memory_limit и убеждаемся, что лимит памяти нужно увеличить.

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

В случае виртуального сервера надо будет отредактировать файл php.ini, найти в нем строку memory_limit, при необходимости раскомментировать ее (убрать точку с запятой в начале строки) и установить нужное значение. Например:

Это означает установку лимита памяти в 512 мегабайт. После этого перезапускаем веб-сервер, снова открываем в браузере страницу info.php и убеждаемся, что лимит увеличился.

Расположение php.ini можно узнать с помощью все того же php_info.

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

Таким образом, если у вашего хостера CloudLinux, то просто увеличьте значение memory_limit в настройках используемой версии PHP.

Но если у хостера не CloudLinux, то можно использовать несколько маленьких хитростей.

Файл .htaccess

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

Функция ini_set()

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

Эта настройка будет работать только для конкретной страницы сайта.

Если провайдер хостинга не разрешает изменение лимита памяти, то эта настройка будет проигнорирована.

Оптимизация алгоритмов и данных

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

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

Часто бывает так, что файл с данными загружается в память целиком с помощью функций языка PHP file() или file_get_contents(), что вызовет ошибку в случае больших файлов. Надо изменить алгоритм таким образом, чтобы данные читались небольшими порциями или построчно.

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

Полезно использовать специальный параметр LIMIT в SQL-запросе для ограничения числа строк данных, получаемых с запросом.

Использование настроек CMS

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

Данная настройка увеличит лимит памяти для всех страниц сайта, включая панель администратора.

Использование оптимизаторов кода

Для языка PHP существуют дополнения (extensions), которые позволяют оптимизировать исполняемый код страницы прозрачно для разработчика и тем самым снимают требования к памяти. К числу таких дополнений относятся, например, OPcache или APCu. На виртуальном сервере нужные дополнения к движку PHP устанавливает сам администратор, а для виртуального хостинга необходимо, чтобы эти дополнения были настроены провайдером.

Случай единичного превышения лимита памяти при обработке большого количества данных

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

К счастью, некоторые провайдеры услуг хостинга предусмотрели такую ситуацию. Они предоставляют функцию turbo-boost, которая увеличивает лимиты памяти и максимального времени выполнения скриптов для конкретного сайта в течение некоторого времени, например, на два часа после активации.

Включив в личном кабинете эту функцию, можно спокойно выполнить ресурсоемкую процедуру импорта товаров или обработки файлов и не беспокоиться о специфических настройках конфигурации или оптимизации алгоритмов.

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

Если ошибку лимита памяти не получается исправить самостоятельно, то в случае использования виртуального хостинга следует обратиться в техническую поддержку. Специалисты смогут уточнить, какие ограничения существуют в рамках текущего тарифного плана, на какой тариф лучше перейти с учетом используемой CMS и нагрузки на сайт. Они смогут помочь, если требуется единичный запуск нужного скрипта, который не проходит из-за данных ограничений.

При возникновении этой проблемы на виртуальном сервере VDS может потребоваться помощь специалиста по администрированию серверов. Специалисты техподдержки провайдера хостинга также могут помочь выполнить нужные настройки сервера.

Источник

Fixing PHP Fatal Error: Allowed Memory Size Exhausted

Table of Contents

1 Introduction: why does Fatal Error happen?

Out-of-memory errors are one of the most common and hard-to-fix problems that PHP developers run into — especially with applications that process large amounts of data — thanks to PHP’s relatively conservative default memory settings. In fact, there are more than 1,300 questions related to PHP memory errors on Stack Overflow alone.

98% of the time this error comes from loading more into memory than what you set up PHP to handle in one process. There are other causes, but these are much less common — very rarely it can be a memory leak if you’re on PHP 5.3 and above.

If you aren’t sure what your PHP memory limit is set to, it’s helpfully included in the error message. The size is reported in bytes, though, so we’ve done some conversions for you:

2 What do I have to do to resolve it?

Your first course of action is to increase your memory limit. Note, this is a temporary debugging producedure. The goal is to increase the memory to a point where we have the application working again for the purpose of then reducing the memory usage. Once you decrease the memory usage you can lower the memory limit it to a value that’s more suitable. Your plan should be to use as little memory as you could practically use where the application works and functions correctly in a production server based on the workload by your users (humans or programmatic). I usually recommend setting the memory limit to something high, like 1GB, assuming you have at least 150% of that free in RAM.

So how do you do this? Simple — increase the memory limit programmatically early on in your code, before your process runs out of memory. If you do it this way, you can give PHP extra memory only when that piece of code gets called rather than increasing the memory limit for all PHP processes.

2.1 Did everything, set it to unlimited and still get the error

Call the ER, because you’re probably going to end up there. No, seriously, here are a couple of things you could do.

First, you need to ask yourself when this started happening. Was it working before, and now it’s not? If so, think about what could have changed. Isolate the problem.

Maybe you didn’t touch your code before the problem appeared. Well, what else could have changed? Are there external dependencies? Perhaps a database, or files that were imported by a user? Put that on your list of suspects and start investigating.

Start off small; begin with what you «think» the problem is and try to prove yourself wrong. If you can’t, move on to the next suspect. See how far you get into your code before it exits prematurely, then start working up the call stack from there ( var_dump debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) if you don’t have Xdebug installed). If you can interactively debug with Xdebug or Zend Debugger, do that and put a breakpoint right before the problem area.

I once had an issue where an Excel file kept running out of memory after being imported. It was working fine for months, but suddenly stopped. I think it took me at least 5 hours of relentless debugging before I discovered the problem: random data that had somehow been inserted into one of the worksheet’s cells by the user. Apparently PHP just went haywire, and I still haven’t discovered the root cause, despite knowing the trigger.

I could’ve saved a lot of time by asking myself what changed. The answer was very obvious — data input by the user and the database. You could have a similar experience.

3 Xdebug, the Swiss Army Knife

After installing Xdebug, all you need to do is refresh the page or, if your code is meant to run in a shell, re-run it in the CLI. PHP will now throw much more informative errors, including a call stack that will tell you exactly where the script stopped with a file path, line number, and even the last function that was called.

Just run the code, and a trace file — including memory usage — will be created even if you run out of memory early.

To locate the problem, begin at the bottom of the trace file and work your way up. Look for deltas (numbers with + or –) with a large number, and keep in mind that they’re shown in bytes. 1024 bytes = 1 kilobyte.

4 PHP Memory management

Here’s a great slide deck on how PHP deals with memory internally.

5 Challenge

Use the following script and try to pinpoint where the problem is. Even better, install Xdebug and generate a trace file.

With all of these tips in mind you should be able to fix any memory exhaustion error. If you’re still having issues, I’d be glad to jump on an AirPair session and help get to the root of the problem so you can focus on what’s important.

Источник

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

I was going crazy with this.

I got the next message:

TODO LIST

Check phpinfo(), got the right php.ini route and edit it. Change memory_limit to

Make sure the value memory_limit changes con phpinfo() with the result:

And also to change it via php like so (before error line):

It says everywhere that memory is set to 128M, but still get that error?

The error is in Swift library (library for sending emails), in abstractSmtpTransport.php, so it’s not my code int’s suposed to work.

Edit: Yes, the previous was done restarting apache.

EDIT 2: @patrick, added that but nothing was echoed

Tryed with lower value, 28M int every file, restarted apache, same error (phpinfo showed new value)

EDIT 3: isn’t it weird that allowed memory is bigger than allocated memory? (despite the fact that allowed memory size is way below real allowed memory asigned)

9 Answers 9

I see my problem is a little bit different from yours, but I’ll post this answer in case it helps someone else. I was using MB as shorthand instead of M when defining my memory_limit, and php was silently ignoring it. I changed it to an integer (in bytes) and the problem was solved.

Edit

As Yaodong points out, you can just as easily use the correct shorthand, «M», instead of using byte values. I changed mine to byte values for debugging purposes and then didn’t bother to change it back.

The value of 262,144 bytes is the key to the diagnosis. You’ll see this magic number pop up in PHP questions all over the place. Why? Because that is the value PHP will end up with as its memory limit if you attempt to update the limit with a value it can’t use. An empty string will produce this memory limit, as will an incorrect unit notation like ‘128MB’ instead of the correct ‘128M’.

262,144 bytes is exactly 256 Kibibytes. Why PHP runs home to that value when it gets confused is beyond me.

isn’t it weird that allowed memory is bigger than allocated memory?

The allocated amount shown is just the most recent allocation attempt, the one that ran afoul of the memory limit. See Allowed memory size in PHP when allocating less.

See if this answer can help you. Particularly the fact that CLI ini could be different than when the script is running through a browser.

In my case neither M or G helped, so I have converted allocated memory to bytes using: https://www.gbmb.org/mb-to-bytes

php.ini:

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

I was trying to up the limit WordPress sets on media uploads. I followed advice from some blog I’m not going to mention to raise the limit from 64MB to 2GB.

I did the following:

Created a (php.ini) file in WP ADMIN with the following integers:

I immediately received this error when trying to log into my WordPress dashboard to check if it worked:

“Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)»

The above information in this chain helped me tremendously. (Stack usually does BTW)

I modified the PHP.ini file to the following:

The major difference was only use M, not MB, and set that memory limit high.

As soon as I saved the changed the PHP.ini file, I saved it, went to login again and the login screen reappeared.

I went in and checked media uploads, ands bang:

I haven’t restarted Apache yet… but all looks good.

Источник

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

This error message is being presented, any suggestions?

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

24 Answers 24

At last I found the answer:

Just add this line before the line where you get error in your php file

It will take unlimited memory usage of server, it’s working fine.

Consider ’44M’ instead of ‘-1’ for safe memory usage.

Here are two simple methods to increase the limit on shared hosting:

If you have access to your PHP.ini file, change the line in PHP.ini If your line shows 32M try 64M: memory_limit = 64M ; Maximum amount of memory a script may consume (64MB)

Your script is using too much memory. This can often happen in PHP if you have a loop that has run out of control and you are creating objects or adding to arrays on each pass of the loop.

Check for infinite loops.

Check the code where the error actually happens as well. Would you expect that line to be allocating a massive amount of memory? If not, try and figure out what has gone wrong.

is never good. If you want to read a very large file, it is a best practise to copy it bit by bit. Try the following code for best practise.

I have faced same problem in php7.2 with laravel 5.6. I just increase the amount of variable memory_limit = 128M in php.ini as my applications demand. It might be 256M/512M/1048M. Now it works fine.

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

If you want to read large files, you should read them bit by bit instead of reading them at once.
It’s simple math: If you read a 1 MB large file at once, than at least 1 MB of memory is needed at the same time to hold the data.

Btw, please don’t do the following code, because that’s bad practice:

You can increase the memory allowed to php script by executing the following line above all the codes in the script:

And also de allocate the unwanted variables in the script.

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть фото php fatal error allowed memory size of 2097152 bytes exhausted. Смотреть картинку php fatal error allowed memory size of 2097152 bytes exhausted. Картинка про php fatal error allowed memory size of 2097152 bytes exhausted. Фото php fatal error allowed memory size of 2097152 bytes exhausted

I notice many answers just try to increase the amount of memory given to a script which has its place but more often than not it means that something is being too liberal with memory due to an unforseen amount of volume or size. Obviously if your not the author of a script your at the mercy of the author unless your feeling ambitious 🙂 The PHP docs even say memory issues are due to «poorly written scripts»

The xdebug documentation is helpful, but it boils down to 3 steps:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *