Когда вашему скрипту не хватает оперативной памяти для его выполнения (точнее он не укладывается в объём, который ему разрешён), возникает ошибка «Allowed memory size of XXX bytes exhausted (tried to allocate YYY bytes)».
Для решения данной задачи предлагаю три варианта на выбор в зависимости от прав доступа на сервере и его конфигурации.
Варианты
Один из этих вариантов вам точно поможет.
Способ первый
В файле настроек РНР (php.ini) пишем:
Обычно для простых смертных этот файл править не дают. Всё зависит от вашего хостинг-провайдера. Да и делать вам там нечего.
Способ второй
В файле настроек сайта (.htaccess) пишем:
php_value memory_limit 100M
При определённой конфигурации сервера вы можете получить ошибку 500 — Internal Server Error.
Способ третий
В теле вашего скрипта (например, config.php) пишем:
<?php ini_set('memory_limit', '100M'); ?>
Самый простой и безопасный ход решения проблемы. Меня выручает постоянно.
Для сайта на WordPress
В начале вашего файла конфигурации wp-config.php
в корне сайта добавьте строку:
<?php define( 'WP_MEMORY_LIMIT', '100M' ); ?>
Errors htaccess PHP WordPress
Время на прочтение
1 мин
Количество просмотров 5.1K
Когда вашему скрипту не хватает оперативной памяти для его выполнения (точнее он не укладывается в объём, который ему разрешён), возникает ошибка «Allowed memory size of XXX bytes exhausted (tried to allocate YYY bytes)».
Для решения данной задачи предлагаю три варианта на выбор в зависимости от прав доступа на сервере и его конфигурации.
Один из этих вариантов вам точно поможет.
Способ первый:
В файле настроек РНР (php.ini) пишем:
memory_limit = 100M
Обычно для простых смертных этот файл править не дают. Всё зависит от вашего хостинг-провайдера. Да и делать вам там нечего.
Способ второй:
В файле настроек сайта (.htaccess) пишем:
php_value memory_limit 100M
При определённой конфигурации сервера вы можете получить ошибку 500 – Internal Server Error.
Способ третий:
В теле вашего скрипта (например, config.php) пишем:
<?php
ini_set('memory_limit', '100M');
?>
Самый простой и безопасный ход решения проблемы. Меня выручает постоянно.
«Fatal error: Allowed memory size…»
Переводится, как «неустранимая ошибка: допустимый размер памяти…». Данная ошибка говорит о том, что скрипт превысил допустимый размер выделяемый ему оперативной памяти.
Fatal error: Allowed memory size of 408933426 bytes exhausted (tried to allocate 3009682 bytes)
Данная ошибка показывает:
- 408933426 bytes — допустимый размер памяти
- 3009682 bytes — сколько не хватает памяти.
Ошибка исчерпания лимита памяти возникает, когда сайт потребляет больше оперативной памяти, чем ему доступно (указано в php.ini).
Как исправить ошибку «Fatal error: Allowed memory size…»?
Наш хостинг предоставляет возможность пользователю менять настройки PHP. Для устранения данной ошибки, нам нужно будет увеличить параметр memory_limit для версии PHP, на которой работает Ваш сайт. Узнать версию Вашего сайта Вы можете в панели хостинга в разделе «WWW» — пункт «WWW-домены».
После того, как мы узнали версию PHP, нам нужно перейти в раздел «WWW» — пункт «PHP», выбираем нужную нам версию и нажимаем кнопку «Настройка».
В открывшемся окне будут представлены параметры PHP, нас интересует memory_limit. Сейчас напротив поля memory_limit будет указано доступное количество оперативной памяти. Чтобы изменить этот параметр, нам нужно нажать на него и сверху выбрать кнопку «Изменить» или кликнуть на него 2 раза и ввести нужное нам количество оперативной памяти.
Будьте осторожны на каждом тарифе хостинга есть свое ограничение по лимиту оперативной памяти. Ознакомиться с данными ограничениями Вы можете на этой странице.
Также узнать версию PHP и объём доступной памяти можно с помощью функции phpinfo(). Для этого нужно создать php-скрипт, например с именем: t.php. После создания, нужно будет добавить в него следующий код:
<?php
phpinfo();
?>
После добавления кода, нужно загрузить файл в директорию сайта. И при открытии сайта, дописать к адресу /t.php (Например, ваш_сайт.ru/t.php). После чего откроется страница, где будут указаны все параметры PHP.
If by increasing the memory limit you have gotten rid of the error and your code now works, you’ll need to take measures to decrease that memory usage. Here are a few things you could do to decrease it:
If you’re reading files, read them line-by-line instead of reading in the complete file into memory. Look at fgets and SplFileObject::fgets.
Upgrade to a new version of PHP if you’re using PHP 5.3. PHP 5.4 and 5.5 use much less memory.
Avoid loading large datasets into in an array. Instead, go for processing smaller subsets of the larger dataset and, if necessary, persist your data into a database to relieve memory use.
Try the latest version or minor version of a third-party library (1.9.3 vs. your 1.8.2, for instance) and use whichever is more stable. Sometimes newer versions of libraries are written more efficiently.
If you have an uncommon or unstable PHP extension, try upgrading it. It might have a memory leak.
If you’re dealing with large files and you simply can’t read it line-by-line, try breaking the file into many smaller files and process those individually.
Disable PHP extensions that you don’t need.
In the problem area, unset variables which contain large amounts of data and aren’t required later in the code.
FROM: https://www.airpair.com/php/fatal-error-allowed-memory-size
This article we will cover one of the most common WordPress errors: “Fatal error: Allowed memory size exhausted”. What causes it and the different ways to resolve it.
Analyzing the Error
By default, a new WordPress install will have an allocation of 64M, but this is not always enough.
In most cases, once you install a new theme or plugin that requires a higher server memory limit, of which is not allocated within your WordPress environment, then you are likely to encounter this error within your browser, once you try accessing your website.
A sample format of the error would be rendered as:
Fatal error: Allowed memory size of 33455443 bytes exhausted (tried to allocate 2211214 bytes) in C:wamp64wwwwp-includesfunctions.php on line 5231
Note that you will only be in a position to have a view of the error if you have enabled debugging within your WordPress environment. Otherwise, a “White Screen” would be rendered. Enabling debugging within your WordPress environment can be accomplished from the wp-config.php
file.
You can access the wp-config.php
file within the root of your WordPress install. As per the sample error above, of which is within a local install, the file will be within the directory path C:wamp64www
If your website is already uploaded, you can access the file using an FTP client software such as Filezilla or WinSCP. Connecting to your website via FTP requires a specific set of credentials. You can consult your host on the required FTP login details if you are not in a position to trace these on your end.
As an alternative, you can also access the file via the control panel provided by your web hosting and navigate to the /public_html/
folder where you will find the file in place.
Once you are in a position to replicate the error, then you can proceed to determine a way on how to go about fixing the error.
Fixing the Error
There are a couple of ways on how to go about resolving this error. These include:
- Editing the
wp-config.php
file - Editing the
php.ini
file - Editing the
.htaccess
file
In these three methods, the first step would be in analyzing the amount of additional memory required. This would be different across different installs.
Let’s cover each of these methods:
1. Editing the wp-config.php
file
Here you will need to edit the wp-config.php file. Prior to this, I would recommend creating a backup of this file by downloading it your local computer or else saving it to your desktop if your website is within a local install. This would serve as a safety precaution in case you would wish to restore to an earlier state.
With this accomplished, you can then add the code below just prior to the line that says “That’s all, stop editing! Happy blogging”
define( 'WP_MEMORY_LIMIT', '256M' );
The M means megabytes. A 256M memory allocation would be appropriate for most installs. You can, however, have the value raised higher to 512M, depending on the extra memory allocated needed.
Once this is done, save your changes and try accessing your website URL to see if the error is resolved. If so, you should have a view of your site content or else the accessed URL content.
In some instances, this method may not work. This happens in instances whereby you are on a shared hosting and the hosting provider does not allow such a change. In such a situation you may need to consult your hosting provider on this issue.
2. Editing the php.ini
file
The php.ini
file is a configuration file that is read once a PHP script is executed or else when PHP starts.
You can use this file to control resource limits such as the required memory in our case here.
On a live install, the file can be accessed within the root of your install, that is within the /public_html/
folder. Note that the file is not installed by WordPress but in most cases set up by your host. If you are using CPanel as your control panel, for example, make sure the checkbox for “Show Hidden Files” is checked and then click Go. You may check into this article on how to go about editing the file.
Before editing the file, kindly preserve a backup to it by downloading it to your computer.
Once this is done, open the file, add or edit the following line:
memory_limit 512M
After, press save and close.
As for local installs, the location of the file will depend on the Local server in use. In our sample here using WAMP, you will need to:
- Start WAMP server and wait for the WAMP icon in the taskbar to turn green.
- Left click on the icon.
- Select PHP > php settings > memory limit.
- Change the value to 256.
This will by default change the setting in php.ini.
3. Editing the .htaccess
file
The .htaccess
file is a file located within the root of your WordPress files.
Again we would advise you to carry out a backup of this file.
If the alteration to the php.ini
file did not work, you can choose to edit this file.
You will need to add or edit the following code to the bottom of the file:
php_value memory_limit 256M
With this done, you can then save your changes and check if the error is resolved.
Conclusion
In any case, the methods above do not work out for you, or else you would not wish to carry out these changes yourself, I would recommend on consulting your hosting provider on this so that they can have the limit increased from their end.
Ошибка 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.