Ошибка allowed memory size of

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.

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.

Время на прочтение
1 мин

Количество просмотров 5.9K

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

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

Introduction

The “allowed memory size exhausted” fatal PHP error means that a PHP script exceeded the set PHP memory limit and thus failed. This can result in 500 errors or broken functionality within a webpage.

The error will be available either in your website Nginx or OpenLiteSpeed error log and will look like this:

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 10485760 bytes) in {script-path-here} on line 370

Fortunately, this is a quick and easy fix, and below we’ll cover the two scenarios that you may encounter.

Table of Contents

  • Understanding the PHP Memory Limit
  • 1. Website PHP Memory Limit Exhausted
  • 2. PHP CLI Memory Limit Exhausted

Understanding the PHP Memory Limit

PHP.net breaks PHP memory_limit down like this: 

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1.

This setting is per-script, which means that other scripts on the same page may execute like normal (since they have their own memory allocation), and only a portion of the page will be broken. In other cases, it could cause a 500 HTTP error, and the page may fail to load altogether.

More often than not, when we see this error, it’s usually due to a WordPress plugin.

How Much Should You Increase It?

Increase the memory enough to resolve the error from happening, and then simply leave it there. If it requires more than 512MB, then this is potentially problematic and you should address the issue directly within your code base (usually, it’s finding a replacement for a plugin).

Setting a high memory limit does not provide any additional benefit and can actually result in issues that are otherwise easy to avoid. By setting a high memory limit you’re allowing the possibility for poorly written code to consume all of your RAM and potentially cause performance issues across ALL of the sites on this server, and you would also be oblivious to any future code issues that may arise.

1. Website PHP Memory Limit Exhausted

GridPane sets a default size of 256MB, which is plenty for almost all use cases, even WooCommerce. This is fairly standard for the industry.

It is generally better to find and fix the code responsible for needing more memory, but you can also easily increase the PHP memory limit inside your website customizer > PHP INI settings.

To get started, navigate to the Sites page inside your account and click on the name of the website to open up the customizer. Here, you’ll find the memory setting located inside PHP > PHP INI here:

Enter the new memory limit and hit update.

Alternative Option: Set via GP-CLI

Alternatively, you can set this via GP-CLI with the following command:

gp stack php -site-mem-limit {integer} {site.url}

For example:

gp stack php -site-mem-limit 512 gridpane.com 

2. PHP CLI Memory Limit Exhausted

It’s far rarer to encounter this error, but it’s possible you could run into it using WP-CLI on the command line.

Step 1. Check php.ini used

Connect to your server via SSH and run the following:

wp --info

Step 2.1 Nginx

On Nginx, the output will look as follows, and we’re specifically looking for the highlighted line:

OS: Linux 4.15.0-197-generic #208-Ubuntu SMP Tue Nov 1 17:23:37 UTC 2022 x86_64
Shell: /bin/bash
PHP binary: /usr/bin/php8.0
PHP version: 8.0.25
php.ini used: /etc/php/8.0/cli/php.ini
MySQL binary: /usr/bin/mysql
MySQL version: mysql Ver 8.0.30-22 for Linux on x86_64 (Percona Server (GPL), Release '22', Revision '7e301439b65')
SQL modes:
WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: /root
WP-CLI packages dir: /root/.wp-cli/packages/
WP-CLI cache dir: /root/.wp-cli/cache
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.7.1

The current CLI PHP version across GridPane servers is 8.0 as above. We can increase the memory_limit by editing this file with:

nano /etc/php/8.0/cli/php.ini

Step 2.2 OpenLiteSpeed

On OpenLiteSpeed, the output will look as follows, and we’re specifically looking for the highlighted line:

OS: Linux 5.4.0-122-generic #138-Ubuntu SMP Wed Jun 22 15:00:31 UTC 2022 x86_64
Shell: /bin/bash
PHP binary: /usr/local/lsws/lsphp80/bin/php
PHP version: 8.0.26
php.ini used: /usr/local/lsws/lsphp80/etc/php/8.0/litespeed/php.ini
MySQL binary: /usr/bin/mysql
MySQL version: mysql Ver 8.0.30-22 for Linux on x86_64 (Percona Server (GPL), Release '22', Revision '7e301439b65')
SQL modes:
WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: /root
WP-CLI packages dir: /root/.wp-cli/packages/
WP-CLI cache dir: /root/.wp-cli/cache
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.7.1

The current CLI PHP version across GridPane servers is 8.0 as above. We can increase the memory_limit by editing this file with:

nano /usr/local/lsws/lsphp80/etc/php/8.0/litespeed/php.ini

Step 3. Adjust and Save

Use the down arrow key to scroll down to “Resource Limits“, and you’ll find the setting under:

; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit = XXX

Edit the limit value (numbers only), then save the file with CTRL+O followed by Enter. Exit nano with CTRL+X.

Step 4. Restart PHP

Finally, restart the appropriate PHP version with:

4.1  NGINX 
gp php {php.version} -restart

For example:

gp php 8.0 -restart
4.2 OPENLITESPEED
touch /usr/local/lsws/admin/tmp/.lsphp_restart.txt
systemctl restart lsws

PHP memory limits prevent poorly written scripts from using all of the memory resources on the server.  To avoid PHP memory limit errors all WordPress sites should set memory limit values to 256MB via the wp-config.php, .htaccess or php.ini files.

Adjusting this value will satisfy the memory requirements of popular plugins like WooCommerce, WPML, Multisite and site builders. This prevents your site or admin dashboard from displaying the Fatal error: Allowed memory size of XXXXXXXX bytes exhausted (tried to allocate XXXX bytes) error message.

The default 40MB from WordPress is simply not enough memory to meet the demands of complex plugins and administrative actions in your WordPress dashboard. Thankfully there are 4 ways you can adjust these limits in WordPress.

Fixing PHP Memory Errors

1. PHP Memory Limit Error Causes

In order to prevent poorly written scripts from using up all the memory resources on your server a maximum memory limit (per script) is enabled by default. Out of memory errors are caused when scripts try to utilize more memory than wordpress has allocated.

By default wordpress sets PHP memory limits to 40MB for a single site and 64MB for multisites. Scripts that violate those thresholds cause error messages to show up like this one.

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 6969 bytes)

2. Recommended Memory Limit Settings

Changing your memory limit setting increases PHP Memory only for WordPress, not other applications. Furthermore, you will need to change the memory values for both your public pages and admin dashboard.. When executing administrative tasks (admin dashboard) more memory is often necessary.

A 256MB Limit and 512MB MAX Limit (wp-config.php) would be appropriate on shared hosting. Popular plugins like WooCommerce, WPML, multisite and most site builders require 256M to run properly.

If you are on a Cloud, VPS or Dedicated server you might wish to increase memory limits for public and admin even further. Limits could be increased to 512M for public pages and 1024M for the admin dashboard.

    • define( ‘WP_MEMORY_LIMIT’, ‘256M’ );
    • define( ‘WP_MAX_MEMORY_LIMIT’, ‘512M’ );

By default, WordPress will attempt to increase memory allocated to PHP to 40MB (located in /wp-includes/default-constants.php) for single site and 64MB for multisite, so the when editing your (located in root directory) wp-config.php you should enter an input higher than 40MB / 64MB respectively.

3. Public vs Admin Memory Limits

WordPress distinguishes between public facing page memory and admin memory by adding “MAX” to the code. It’s a terrible naming scheme dating back to WordPress 2.5, but nobody dares change it now.

  • define(‘WP_MEMORY_LIMIT’, ‘256M’); Public Page Memory
  • define( ‘WP_MAX_MEMORY_LIMIT’, ‘512M’ );  Admin Dashboard Memory

4. Bytes to MegaBytes Conversion Chart

If your website sends out an error message with specific byte sizes you can use this handy Bytes To Megabytes Conversion Calculator tool to estimate what memory limit has been exceeded.

1 byte is also equal to 0.00000095367432 megabytes = 2-20 megabytes in base 2 (binary) system.

Memory Limit Bytes Megabytes
PHP: Fatal Error: Allowed Memory Size of 4194304 Bytes Exhausted 4 MB
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 1024 MB (1GB)

5. Accessing wp-config.php / php.ini / .htaccess

There are three ways you can easily access the needed wordpress files to adjust memory limits. You can access files using your control panel (Cpanel) after logging into your host, use an FTP program like Filezilla or install a wordpress plugin.

Navigate to the root directory of your wordpress installation. If you are in the control panel you might to click on the “View” link in the upper right corner and make sure the checkmark for “show hidden files” is selected.

  1. Cpanel – Control panel in your hosting admin dashboard
  2. Filezilla – Free FTP software to transport files
  3. WPCF – Free plugin that allows you to edit wp-config

6. Edit Your wp-config.php File

Accessing wp-config through Cpanel is the easiest method of changing your memory limit values in wordpress. It is located in the root directory of your wordpress installation after scrolling down to the bottom. Right click on the wp-config.php file, paste the memory limit values we provided and click save.

Alternatively you can use the search option (upper right corner) by typing in “wp-config” exactly as show and clicking “Go”. You also have the option to search through “All Your Files” or in a specific directory by clicking the drop down arrow.

wp-config cpanel

Add this right above the line that says  /* That’s all, stop editing! Happy publishing. */

define('WP_MEMORY_LIMIT', '256M');
define('WP_MAX_MEMORY_LIMIT', '512M');

wp-config memory limit code

Your server PHP memory limit will be different than your wordpress memory limit. Your host will set the server memory limit for all applications. Editing the wordpress memory limit settings only applies to wordpress.

7. Edit Your php.ini File

If you have access to your php.ini file, change the memory limit value. If you don’t have a php.ini file you can create one. If your line shows 40MB or 64MB try changing the value to “256M”

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

Creating a php.ini file can be done by navigating to your yourdomain/wp-admin and clicking +FILE (top left corner) in cpanel. Name the newly created file “php.ini” and click “create new file”.

8. Edit your .htaccess File

If you don’t have access to PHP.ini or prefer not to edit wp-config.php try adding this to an .htaccess file:

php_value memory_limit 256M

 
The .htaccess file is located in your root directory. You can add your code right above “# END WordPress” at the bottom of the file.

9. Edit Using WPCF Plugin

wp-config cpanel

Its generally bad to use plugins for tasks that you can easily do manually. If you just can’t seem to figure out how to change the wp-config using cpanel or FTP you can use a handy plugin called WordPress Config File Editor (WPCF).

After downloading and activating the plugin you can edit the wp-config by editing the memory limit (public pages) and max memory limit (admin dashboard) in the field boxes provided. Recommended values are 256M and 512M respectively.

Should you not feel comfortable in trying the above methods, or the above did not work for you, you need to talk to your hosting about having them increase your memory limit.

Some hosts do not allow changing your PHP memory limit, in which case you would have to contact your hosting support by emailing or opening a support ticket. Other (shared) hosts put a cap of 756M on the allowed memory limit. If you have Cloud, VPS or a Dedicated server these limits can be increased even further.

11. Troubleshooting Memory Limit Errors

If you have recently added a plugin to wordpress and encountered the fatal error memory limit message there is a high probability the culprit is the plugin you just installed. If you have increased your memory limits to 1024M and are still getting fatal error messages, its time to get serious about troubleshooting.

What about memory error messages that seemingly come out of nowhere?

Without getting too technical two options exist for detecting plugins that eat up server resources. One well known scan is P3 Profiler which scans the load time and query count of all the plugins used during your site load. The only trouble is its outdated, with 3 major WordPress releases since its last update.

A second option Query Monitor requires a bit more technical knowledge. It provides a wealth of information about your server and database configuration, peak memory usage and query count. This information combined with a basic waterfall chart from GT Metrix or Pingdom can help out big time.

In case you didn’t already know certain plugins are well known resource hogs. Here are some that make the list.

  • Wordfence (Security/Firewall)
  • BackupBuddy (Backup Programs)
  • Site Builders (Divi, Elementor, Flatsome, Beaver)
  • WooCommerce (Ecommerce store)
  • BuddyPress (Forums & Message Boards)
  • Disqus (Commenting)
  • Add This (Social Media)
  • Revolution Slider (Slider Plugins)

12. Memory Limit Key Points

  1.  Wordpress separates memory limits by public pages (WP_MEMORY_LIMIT) and admin pages (WP_MAX_MEMORY_LIMIT)
  2. Admin pages (dashboard) require more memory than public pages (your website).
  3. By default WordPress allocates 40MB of memory. Change this to 256M (public pages) and 512M (admin pages) in wp-config.php
  4. Several plugins are known resource hogs and should be avoided or substituted for light weight options.
  5. WooCommerce, WPML, Multisite, Forums and Site Builders require a minimum of 256MB.
  6. Most hosting companies allow you to increase memory limits (some don’t) so contact your host as needed.
  7. WordPress memory limits are set on a per script basis, not the combined total. Limits are ultimately capped by your server resources.
  8. The easiest way to change memory limits is through cpanel and editing wp-config.php file in your root directory.

Понравилась статья? Поделить с друзьями:
  • Ошибка alarm system service required
  • Ошибка airbag соната тагаз
  • Ошибка airf на бобкете
  • Ошибка alert configuration script failed 2000
  • Ошибка airbag хендай акцент