Ошибка php fatal error allowed memory size of

Время на прочтение
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');
?>

Самый простой и безопасный ход решения проблемы. Меня выручает постоянно.

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

Когда вашему скрипту не хватает оперативной памяти для его выполнения (точнее он не укладывается в объём, который ему разрешён), возникает ошибка «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

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 Мб (с серьезным запасом на будущее).

Понравилась статья? Поделить с друзьями:
  • Ошибка package does not exist
  • Ошибка php failed to open stream
  • Ошибка p704 на автономке планар
  • Ошибка php eval d code on line
  • Ошибка p5353 на ваз 2114