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
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”.
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 beetc/php.ini
.
- Next, You find the line “memory_limt =”
- Finally, You adjust the value accordingly and save it.
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 of XXX bytes exhausted»
- Варианты
- Способ первый
- Способ второй
- Способ третий
- Для сайта на WordPress
- Fatal error: Allowed memory size of * bytes exhausted. Варианты решения
- Содержание статьи:
- Причины ошибки Allowed memory size
- Увеличение WP_MEMORY_LIMIT в php файлах
- WP_MEMORY_LIMIT в wp-config.php
- Увеличение memory_limit в прочих конфигурационных файлах
- memory_limit в php.ini
- memory_limit в .htacess
- Ошибка — Fatal error: Allowed memory size
- Решение проблемы с ограничением памяти
- Файл php.ini
- Через .htaccess в корне сайта
- Как посмотреть, сработало ли?
- Fixing PHP Fatal Error: Allowed Memory Size Exhausted
- Table of Contents
- 1 Introduction: why does Fatal Error happen?
- 2 What do I have to do to resolve it?
- 2.1 Did everything, set it to unlimited and still get the error
- 3 Xdebug, the Swiss Army Knife
- 4 PHP Memory management
- 5 Challenge
Три способа решения проблемы «Fatal error: Allowed memory size of XXX bytes exhausted»
Когда вашему скрипту не хватает оперативной памяти для его выполнения (точнее он не укладывается в объём, который ему разрешён), возникает ошибка «Allowed memory size of XXX bytes exhausted (tried to allocate YYY bytes)».
Для решения данной задачи предлагаю три варианта на выбор в зависимости от прав доступа на сервере и его конфигурации.
Варианты
Один из этих вариантов вам точно поможет.
Способ первый
В файле настроек РНР (php.ini) пишем:
Обычно для простых смертных этот файл править не дают. Всё зависит от вашего хостинг-провайдера. Да и делать вам там нечего.
Способ второй
В файле настроек сайта (.htaccess) пишем:
При определённой конфигурации сервера вы можете получить ошибку 500 — Internal Server Error.
Способ третий
В теле вашего скрипта (например, config.php) пишем:
Самый простой и безопасный ход решения проблемы. Меня выручает постоянно.
Для сайта на WordPress
В начале вашего файла конфигурации wp-config.php в корне сайта добавьте строку:
Суровый русский тимлид. Жил в Магадане, в офисе московских веб студий и в Тульской деревне. Виртуозно знает WordPress, PHP, ООП, Vue.js и вот это вот все.
Делает крутые высоконагруженные сайты, поэтому уже почти захватил весь рынок WordPress разработки в России. Не дает никому делать сайты без спроса.
Ведет блог о разработке, дайджест в телеграмме и в ВК.
Спасибо, в моем случае сработал второй способ, скрипт выдавал ошибку Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 84 bytes) но увеличить обьем выделенной оперативной памяти на своем хостинге я не смог, поэтому прописав напрямую в скрипте дерективу удалось обойти ограничение и скрипт отработал отлично. Спасибо!
Источник
Fatal error: Allowed memory size of * bytes exhausted. Варианты решения
Ошибки в работе веб-приложений и веб-сайтов — вещь, которая может доставить много проблем. То, что узнать о такой ошибки владелец ресурса может куда позже пользователей, ещё более усугубляет ситуацию. В рамках данной статьи мы продолжим тему, которая поднималась в публикации Ошибка #1273 — Unknown collation: utf8mb4. Обновляем MySQL в Denwer, то есть поговорим о том, как исправить одну из распространённых ошибок, с которой сталкиваются веб-мастера.
Задача текущего топика — решить проблему исчерпания лимита памяти с последующим выводом ошибки Fatal error: Allowed memory size of * bytes exhausted.
Содержание статьи:
Причины ошибки Allowed memory size
Представим ситуацию: мы обновляем SQL базу нашего сайта, импортируем созданный бэкап , но буквально через пару секунд после начала загрузки процесс останавливается и выводится ошибка.
Или другая ситуация: нужно нам авторизоваться на собственном сайте, открываем админ-панель , но вместо формы входам получаем ошибку выполнения.
А вот вообще критичный вариант: пользователь из поисковой выдачи пытается перейти на сайт, но вместо страницы с контентом получает ошибку.
Все три вышеописанных случая могут иметь разные причины, но также во всех трёх случаях причиной может быть нехватка выделенной памяти для выполнения php-кода. Если проблема именно в недостаточном количестве памяти, то ошибка, которая выведется на экран, будет примерно следующего содержания:
где:
1* — допустимый для выделения объём памяти, в байтах;
2* — объём памяти, который необходим для дополнительного выделения, в байтах;
3* — путь до файл, при выполнении которого был исчерпан лимит выделенной памяти;
4* — номер строки в файле 3*, при выполнении которой был исчерпан лимит выделенной памяти.
Вот пример ошибки, выпадающей при попытке импорта базы сайта WordPress с хостинга на Денвер для работы в локальной сети, о возможности которой говорилось в статье Денвер в локальной сети. Локальный сайт на телефоне:
Из скриншота ошибки можно понять, что при попытке выполнения 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.
- Открываем файл, находящийся по следующему пути:
и, если речь идёт о Денвере, соответственно:
В коде страницы сразу после тега WP_MEMORY_LIMIT в default-constants.php
Как ясно из названия файла, default-constants.php отвечает за элементарные параметры веб-ресурса, что называется, «по умолчанию«. Разумеется, что это касается и значения величины WP_MEMORY_LIMIT.
- Открываем следующий файл на хостинге:
или файл на Денвере:
Увеличение memory_limit в прочих конфигурационных файлах
Теперь разберём варианты устранения ошибки Allowed memory size exhausted через редактирование двух других файлов, которые используются не только при настройке CMS WordPress.
memory_limit в php.ini
Файл php.ini позволяет настраивать большое количество переменных, значение объёма выделенной памяти входит в их число. Для начала необходимо выяснить, где именно находится php.ini на нашем сервере, это зависит от операционной системы (разумеется, речь идёт об ОС сервера).
Любым текстовым редактором создаём php-файл со следующим содержим:
Сохраняем файл с произвольным именем, например, phpinfo.php. Готовый файл можно скачать в прикреплённом к статье архиве: phpinfo.
Теперь извлекаем из архива файл и помещаем его в корневую директорию сайта, то есть в каталог /public_html/ или /www/
Далее в адресной строке набираем адрес нашего сайта и через слеш имя файла phpinfo.php, например:
Переходим по адресу и получаем в ответ примерно такую страницу:
В первую очередь смотрим на значение строчки Loaded Configuration File , если путь до php.ini там не прописан, то обращаем внимание на параметр Configuration File (php.ini) Path . Путь может быть указан разный. Вот только несколько возможных примеров:
- /public_html/wp-admin/php.ini
- /etc/php/php.ini
- WebServersusrlocalphp5php.ini
Теперь приступаем к увеличению выделенной памяти:
- Переходим в каталог, где хранится файл php.ini и открываем сам файл для редактирования. Если такого файла в каталоге нет, создаём его любым текстовым редактором.
- Добавляем в файл следующий код (всё, что указано после символа точки с запятой, является комментарием и не обязательно к добавлению):
Готовый файл можно скачать из прикреплённого к статье архива: php
memory_limit в .htacess
Заключительный в рамках данной статьи способ увеличения выделяемой памяти для выполнения скрипта — использование файла .htacess.
В упомянутой выше статье о настройке работы Денвер в локальной сети мы уже касались данного файла, поэтому здесь не будем уделять ему лишнего внимания. Отметим только то, что нас интересует для текущих действий, а именно то, что файл .htacess хранится в корневой директории сайта . Приступим к его редактированию:
- Переходим в корневую директорию сайта и открываем файл .htacess любым удобным текстовым редактором.
- Добавляем в файл самой верхней строчкой следующий код:
- Сохраняем изменения в файле и проверяем работу сайта.
На этом всё. Мы рассмотрели 4 способа исправления ошибки Fatal error: Allowed memory size of * bytes exhausted.
Источник
Ошибка — Fatal error: Allowed memory size
Ошибка 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:
Через .htaccess в корне сайта
Добавьте в самом начале строку php_value memory_limit 256M. Во время выполнения PHP, запишите перед тяжелыми операциями в php-файл следующую строчку
Как посмотреть, сработало ли?
Откройте в панели управления Joomla информацию о системе
И найдите строку memory_limit
Тоже самое можно сделать через команду .
Если не получилось.
В случае, если рекомендации из статьи не помогли вам (возможно хостинг не дает таких прав), то обратитесь с этим вопросом к техподдержке вашего хостинга. Если хостер отказал, то рассмотрите вариант с выполнением тяжелых операций на локальной машине. Затем результат работы перенесите на ваш продуктивный сайт в интернете.
Альтернатива
Также оптимизации по памяти можно добиться установкой APC. Он уменьшает потребление памяти в
1,5-2 раза и ускоряет работу всего сайта в целом. Для нормальной работы Joomla + JBZoo обычно хватает 64 Мб (с серьезным запасом на будущее).
Источник
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:
- 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
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.
Also, never do these tests on a production server unless you’re sure you have plenty of RAM and you fully understand how web server processes consume memory. You could easily bring a server to its knees if there are many concurrent processes running, each using a high amount of memory. I would never, ever recommend setting the memory limit to -1 (unlimited) in a production environment. That’s a recipe for disaster. Don’t make that newbie mistake.
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.
- 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.
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
In any situation, there’s one tool you can count on to help diagnose how much memory you’re using and where in your code large amounts of memory are being used: Xdebug. You can install it using package managers like yum , apt-get , port , and homebrew ; install a pre-built binary; use pecl ; or simply compile it yourself.
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.
If you want more detailed information you’ll need to generate what’s called a «trace file.» To do this, set the xdebug.auto_trace and xdebug.show_mem_delta config directives to 1 . Trace files are normally saved in /tmp or /var/tmp , but you can check the output path by looking at the xdebug.trace_output_dir directive in phpinfo() .
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.
Once you’re finished debugging, make sure to set xdebug.auto_trace back to 0 . Trace files can become very large, very quickly, and eat up disk space.
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.
Источник
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.
- Cpanel – Control panel in your hosting admin dashboard
- Filezilla – Free FTP software to transport files
- 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.
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');
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
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
- Wordpress separates memory limits by public pages (WP_MEMORY_LIMIT) and admin pages (WP_MAX_MEMORY_LIMIT)
- Admin pages (dashboard) require more memory than public pages (your website).
- By default WordPress allocates 40MB of memory. Change this to 256M (public pages) and 512M (admin pages) in wp-config.php
- Several plugins are known resource hogs and should be avoided or substituted for light weight options.
- WooCommerce, WPML, Multisite, Forums and Site Builders require a minimum of 256MB.
- Most hosting companies allow you to increase memory limits (some don’t) so contact your host as needed.
- WordPress memory limits are set on a per script basis, not the combined total. Limits are ultimately capped by your server resources.
- The easiest way to change memory limits is through cpanel and editing wp-config.php file in your root directory.