Fatal error allowed memory size of 134217728 bytes exhausted tried to allocate 4096 bytes

I have a bunch of client point of sale (POS) systems that periodically send new sales data to one centralized database, which stores the data into one big database for report generation. The clien...

The most common cause of this error message for me is omitting the «++» operator from a PHP «for» statement. This causes the loop to continue forever, no matter how much memory you allow to be used. It is a simple syntax error, yet is difficult for the compiler or runtime system to detect. It is easy for us to correct if we think to look for it!

But suppose you want a general procedure for stopping such a loop early and reporting the error? You can simply instrument each of your loops (or at least the innermost loops) as discussed below.

In some cases such as recursion inside exceptions, set_time_limit fails, and the browser keeps trying to load the PHP output, either with an infinite loop or with the fatal error message which is the topic of this question.

By reducing the allowed allocation size near the beginning of your code you might be able to prevent the fatal error, as discussed in the other answers.

Then you may be left with a program that terminates, but is still difficult to debug.

Whether or not your program terminates, instrument your code by inserting BreakLoop() calls inside your program to gain control and find out what loop or recursion in your program is causing the problem.

The definition of BreakLoop is as follows:

function BreakLoop($MaxRepetitions=500,$LoopSite="unspecified")
    {
    static $Sites=[];
    if (!@$Sites[$LoopSite] || !$MaxRepetitions)
        $Sites[$LoopSite]=['n'=>0, 'if'=>0];
    if (!$MaxRepetitions)
        return;
    if (++$Sites[$LoopSite]['n'] >= $MaxRepetitions)
        {
        $S=debug_backtrace(); // array_reverse
        $info=$S[0];
        $File=$info['file'];
        $Line=$info['line'];
        exit("*** Loop for site $LoopSite was interrupted after $MaxRepetitions repetitions. In file $File at line $Line.");
        }
    } // BreakLoop

The $LoopSite argument can be the name of a function in your code. It isn’t really necessary, since the error message you will get will point you to the line containing the BreakLoop() call.

How To Fix PHP Fatal Error Allowed Memory Size

You may encounter one of the common errors when running the PHP website source code. And in this article, I will guide you to fix PHP Fatal Error: Allowed Memory Size.

Cases of this error in Magento 2 are also common. For example: Install Theme, Install Extension,…

When encountering this error, an error message will appear:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) in C:xampphtdocsmagento232vendoroyejorgeless.phplibLessTreeDimension.php on line 21
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) in C:xampphtdocsmagento232vendoroyejorgeless.phplibLessTreeDimension.php on line 21

Message Error Allowed memory size

Reason

The cause of this error is because the PHP process is executing using larger RAM resources that we have specified in the php.ini file through “memory_limit”.

Reason of error

This is the configuration table of “memory_limit”.

PHP: Fatal Error: Allowed Memory Size of 8388608 Bytes Exhausted 8 MB
PHP: Fatal Error: Allowed Memory Size of 16777216 Bytes Exhausted 16 MB
PHP: Fatal Error: Allowed Memory Size of 33554432 Bytes Exhausted 32 MB
PHP: Fatal Error: Allowed Memory Size of 67108864 Bytes Exhausted 64 MB
PHP: Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted 128 MB
PHP: Fatal Error: Allowed Memory Size of 268435456 Bytes Exhausted 256 MB
PHP: Fatal Error: Allowed Memory Size of 536870912 Bytes Exhausted 512 MB
PHP: Fatal Error: Allowed Memory Size of 1073741824 Bytes Exhausted 1 GB

You can collate to raise the appropriate value.

  • First, You locate the directory of the php.ini directory. This will usually be etc/php.ini.
  • Next, You find the line “memory_limt =”
  • Finally, You adjust the value accordingly and save it.

Config memory limit value

Good luck!

It comes to the end of the article.

You can view the article How To Install Magento 2.3 In Windows Using XAMPP.

Follow us for more helpful article!

We hope this is a useful blog for you.

Thank you for reading!

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

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

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 71 bytes) in … говорит, что 128 Мб не достаточно (число выше указано в байтах) и его нужно увеличить, либо в указанном месте решить проблему с утечкой памяти.

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

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

  • Оптимизировать скрипт.

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

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

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

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

Файл php.ini

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

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

memory_limit = 256M

Через .htaccess в корне сайта

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

<?php ini_set('memory_limit', '256M');?>

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

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

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

Тоже самое можно сделать через команду <?php phpinfo();?>.

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

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

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

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

This is a guide on how to fix one of PHP’s most common fatal errors: The memory exhausted error.

Here is an example of what this error might look like.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in your-script.php on line 4

PHP’s memory limit.

If you encounter this error, then it means that your PHP script is using too much memory.

If you open the php.ini configuration file that your web server is using, you will come across the following directive.

; Maximum amount of memory a script may consume (128MB)
; http://php.net/memory-limit
memory_limit = 128M

The memory_limit directive defines the maximum amount of memory that a PHP script can consume. In the example above, you can see that the memory_limit directive is set to 128MB.

This means that if one of my PHP scripts consumes more than 128MB in memory, the memory exhausted error will be thrown and the script will die.

If you do not have access to your php.ini file, then you can check what your server’s memory limit is using PHP’s init_get function like so:

echo ini_get('memory_limit');

Recreating this fatal error.

Here is a sample PHP script that I wrote to recreate this error.

$arr = array();
foreach(range(1, 900000) as $i){
    $arr[] = md5($i);
}

In the code above, I looped through 900,000 times using PHP’s range function and then added the md5 hash of each value to an array. After running the script above, I immediately received a fatal error telling me that my script had consumed too much memory.

Common causes of memory errors.

In my experience, the most common cause is a large PHP array. This is especially true in some of the earlier versions of PHP. However, it is worth pointing out that PHP 7 consumes far less memory and is far better-optimized.

A few cases where you might run into this memory exhausted error.

  • Selecting rows from a database and then adding them to a PHP array is fine most cases. However, if you are returning millions of rows and columns, this might become an issue.
  • If your script has large arrays and a lot of loops, there is a good chance that you might run out of memory. This is especially true if you have multiple loops or you are calling a lot of functions inside of those loops.
  • Recursively looping through large multi-dimensional arrays can prove to be an issue.
  • Dynamically creating or resizing images on-the-fly.

From my own personal experience, the most common cause is a large array or a database query that returns far too many rows.

For example, a badly-written JOIN query may return far more rows than you are expecting.

How NOT to fix this error.

On some of the various PHP help forums, you might across people offering solutions such as this.

ini_set('memory_limit', '1024M');

In the above piece of code, we are using PHP’s ini_set function to increase the memory limit.

This is a horrible solution because it does not attempt to fix the underlying problem. It can also cause your web server to run out of RAM.

This line of code attempts to paper over the cracks by giving the script 1GB of memory. In most cases, 1GB is far too much.

A more dangerous example.

ini_set('memory_limit', '-1');

This essentially tells the PHP script that there is no limit to the amount of memory it can use. In other words, it disables PHP’s memory limit.

Fixing memory exhausted errors the right way.

To fix this issue, a better approach is to.

  • Use a debugger such as Xdebug to profile your script and find out where the memory leak is coming from.
  • Make sure that your PHP arrays are not getting too large and that you are avoiding any unnecessary loops. In other words, if you have two loops for the same array, then you should combine them into one loop.
  • Be careful about the amount of data that you are returning from your database. Make sure that you are only selecting table columns that your script is going to use. In other words, specifically name the columns that you want to return. Do not be lazy. By doing a “SELECT * FROM”, you are returning every column.
  • Use PHP’s unset function to destroy variables that you are no longer using, as this can help free up memory. i.e. If you have just looped through a large array that you no longer intend on using, then you can destroy it by passing it into the unset function.

Ошибка о нехватки памяти при выполнении php: Fatal error

Ошибки в работе веб-приложений и веб-сайтов — вещь, которая может доставить много проблем. То, что узнать о такой ошибки владелец ресурса может куда позже пользователей, ещё более усугубляет ситуацию. В рамках данной статьи мы продолжим тему, которая поднималась в публикации Ошибка #1273 — Unknown collation: utf8mb4. Обновляем MySQL в Denwer, то есть поговорим о том, как исправить одну из распространённых ошибок, с которой сталкиваются веб-мастера.
Задача текущего топика — решить проблему исчерпания лимита памяти с последующим выводом ошибки Fatal error: Allowed memory size of * bytes exhausted.

Содержание статьи:

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

Все три вышеописанных случая могут иметь разные причины, но также во всех трёх случаях причиной может быть нехватка выделенной памяти для выполнения php-кода. Если проблема именно в недостаточном количестве памяти, то ошибка, которая выведется на экран, будет примерно следующего содержания:

Fatal error: Allowed memory size of 1* bytes exhausted (tried to allocate 2* bates) in 3* on line 4*

где:
1* — допустимый для выделения объём памяти, в байтах;
2* — объём памяти, который необходим для дополнительного выделения, в байтах;
3* — путь до файл, при выполнении которого был исчерпан лимит выделенной памяти;
4* — номер строки в файле 3*, при выполнении которой был исчерпан лимит выделенной памяти.

Вот пример ошибки, выпадающей при попытке импорта базы сайта WordPress с хостинга на Денвер для работы в локальной сети, о возможности которой говорилось в статье Денвер в локальной сети. Локальный сайт на телефоне:

Ошибка: Fatal error: Allowed memory size of * bytes exhausted (tried to allocate * bates) in * on line *.

Из скриншота ошибки можно понять, что при попытке выполнения 290 строки файла import.lib.php объём выделенной памяти в размере ‪134 217 728‬ байт (или ‪128 Мегабайт) закончился, необходимо дополнительное выделение 41 767 538 байт (39,83 Мегабайт) памяти.
Перевод из байт в Мегабайты осуществляется двойным делением величины на 1024 (после первого деления байт на 1024 мы получим килобайты, после второго — Мегабайты). Обычно, в связи с кратностью памяти (элементарные байт и бит соотносятся в пропорции 1:8), объём памяти в php также указывают кратно 8, то есть 128 Мегабайт увеличивают не до 200, допустим, а до 256 Мегабайт.

Теперь, когда мы знаем, чем вызвана ошибка, нам остаётся исправить её одним из способов. Ниже мы приведём 4 возможных решения проблемы, которые, в свою очередь, условно разобьём на две главы. Все действия проводились с сайтами, построенными на CMS WordPress, однако, при соответствующем подходе, аналогичные шаги могут предприниматься для решения подобной проблемы и на других системах управления.

Увеличение WP_MEMORY_LIMIT в php файлах

В этой главе представим два варианта решения проблемы с нехваткой памяти выполнения кода, оба способа заключаются в редактировании php-файлов сайта, в которых задаётся значение параметра WP_MEMORY_LIMIT.

WP_MEMORY_LIMIT в wp-config.php

Первое решение, которое применяется довольно часто, связано с редактированием файла конфигурации wp-config.php.

  1. Открываем файл, находящийся по следующему пути:
    /public_html/wp-config.php

    и, если речь идёт о Денвере, соответственно:

    /www/wp-config.php
  2. В коде страницы сразу после тега <?php добавляем следующий код:
    //increase WP Memory Limit
    define('WP_MEMORY_LIMIT', '256M');

    Первая строчка — просто комментарий, он даже не обязателен. Но если мы добавляем его, то сам код обязательно должен начинаться с новой строки. Выглядеть это будет примерно так:
    Добавление WP_MEMORY_LIMIT в файл wp-config

  3. Сохраняем изменения в файле и проверяем работу сайта.

WP_MEMORY_LIMIT в default-constants.php

Как ясно из названия файла, default-constants.php отвечает за элементарные параметры веб-ресурса, что называется, «по умолчанию«. Разумеется, что это касается и значения величины WP_MEMORY_LIMIT.

  1. Открываем следующий файл на хостинге:
    /public_html/wp-includes/default-constants.php

    или файл на Денвере:

    /www/wp-includes/default-constants.php
  2. Находим условия выделения памяти по ключевому сочетанию WP_MEMORY_LIMIT. В файле этот параметр встречается несколько раз в связи с изменением его величины в зависимости от различных условий. Нас интересует последнее жёстко присвоенное параметру значение в цепочке кода. Вот как это примерно должно выглядеть:
    Редактирование WP_MEMORY_LIMIT в файле default-constants
  3. Изменяем значение 40M на нужное нам и сохраняем файл.

Увеличение memory_limit в прочих конфигурационных файлах

Теперь разберём варианты устранения ошибки Allowed memory size exhausted через редактирование двух других файлов, которые используются не только при настройке CMS WordPress.

memory_limit в php.ini

Файл php.ini позволяет настраивать большое количество переменных, значение объёма выделенной памяти входит в их число. Для начала необходимо выяснить, где именно находится php.ini на нашем сервере, это зависит от операционной системы (разумеется, речь идёт об ОС сервера).

Любым текстовым редактором создаём php-файл со следующим содержим:

<?php
phpinfo();
?>

Сохраняем файл с произвольным именем, например, phpinfo.php. Готовый файл можно скачать в прикреплённом к статье архиве: phpinfo.
Теперь извлекаем из архива файл и помещаем его в корневую директорию сайта, то есть в каталог /public_html/ или /www/
Далее в адресной строке набираем адрес нашего сайта и через слеш имя файла phpinfo.php, например:

/myphpinfo.php

Переходим по адресу и получаем в ответ примерно такую страницу:

Получение информации о версии и конфигурации php, используемом на сайте

В первую очередь смотрим на значение строчки Loaded Configuration File, если путь до php.ini там не прописан, то обращаем внимание на параметр Configuration File (php.ini) Path. Путь может быть указан разный. Вот только несколько возможных примеров:

  • /public_html/wp-admin/php.ini
  • /etc/php/php.ini
  • WebServersusrlocalphp5php.ini

Теперь приступаем к увеличению выделенной памяти:

  1. Переходим в каталог, где хранится файл php.ini и открываем сам файл для редактирования. Если такого файла в каталоге нет, создаём его любым текстовым редактором.
  2. Добавляем в файл следующий код (всё, что указано после символа точки с запятой, является комментарием и не обязательно к добавлению):
    memory_limit = 256M ; увеличение памяти, выделяемой для работы скрипта

    Готовый файл можно скачать из прикреплённого к статье архива: php

  3. Сохраняем изменения и проверяем работу сайта.

memory_limit в .htacess

Заключительный в рамках данной статьи способ увеличения выделяемой памяти для выполнения скрипта — использование файла .htacess.
В упомянутой выше статье о настройке работы Денвер в локальной сети мы уже касались данного файла, поэтому здесь не будем уделять ему лишнего внимания. Отметим только то, что нас интересует для текущих действий, а именно то, что файл .htacess хранится в корневой директории сайта. Приступим к его редактированию:

  1. Переходим в корневую директорию сайта и открываем файл .htacess любым удобным текстовым редактором.
  2. Добавляем в файл самой верхней строчкой следующий код:
    php_value memory_limit 128M
  3. Сохраняем изменения в файле и проверяем работу сайта.

На этом всё. Мы рассмотрели 4 способа исправления ошибки Fatal error: Allowed memory size of * bytes exhausted.

A common error with Open Source Software like WordPress, Moodle, and Joomla is the php “Allowed memory size error.” Increasing the memory limit is an easy solution. This memory_limit can be changed in the php.ini in the public_html folder in your hosting account. This error can creep up in your website during the normal development process. The following is an example of the error:

Fatal error: Allowed memory size of 268435465 bytes exhausted
(tried to allocate 280559520) in Unknown on line 0

This is due to php variable data being stored in the memory that is not cleared while the php scripts are running.

For those who code their own sites: Coders use the unset() function to clear variable data that is no longer needed; however, with open source software, you will not want to alter any code.

How to fix the “Allowed memory size Error”

The php memory resource can be increased in the php.ini located in the public_html. The following steps will explain how to set the php.ini to allow a larger amount of memory use.

  1. Login to your cPanel
  2. Go to the File Manager.
  3. Select the Web root (public_html/www) directory and click Go.
  4. Find the php.ini file in the public_html.

    Note! If you do not have a php.ini in your public_html files, you can have our tech support staff restore the php.ini to your public_html directory.

    Open the php.ini with the code editor.

  5. Find the following section in the php.ini file.
    max_execution_time = 30
    max_input_time = 60
    memory_limit = 128M

    Try increase the memory_limit value to 256M.

    If the php memory_limit is already at 256M, you can increase it to 512M.

    Save the changes.

  6. In order for your memory limit to take effect you will need to make the php.ini recursive.

    Important! Making the php.ini recursive is an important step. If you do not know how to do this, please see our article on Make the php.ini recursive in the .htaccess.

    Now visit the site. You should not see the “Allowed memory size” error anymore. If the error still shows on your website, there may be a setting within the software itself that is overriding the change or the php.ini in the public-html may be overriden by another setting elsewhere. If this is the case, you can contact our our tech support staff to have them look into the error further.

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

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

  • Fatal error address life is strange
  • Fatal error a1020 cannot find link exe
  • Fatal error a1010 unmatched block nesting
  • Fatal error a1008 unmatched macro nesting
  • Fatal error a1007 nesting level too deep

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

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