Mysql fatal error allowed memory size

This article will explain how to fix the Fatal error: Allowed memory size exhausted error.

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.

Ошибка о нехватки памяти при выполнении 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.

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.

<?php
    ini_set('memory_limit', '1024M'); // or you could use 1G
  • 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.

<?php
function get_usage_in_kb(){
    echo memory_get_usage()/1024.0 . " kb n";
}

class Profiler
{
    protected $startTime = 0;
    public function timerStart(){
        $this->startTime = microtime(true);
    }

    function timerEnd(){
        echo number_format( (microtime(true) - $this->startTime)*1000, 2 ), ' ms';
    }
}

class ProfilerHolder {
    protected $profiler;

    public function __construct( Profiler $profiler ){
        $this->profiler = $profiler;
    }
}

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

$profiler = new Profiler();

$profiler->timerStart();

get_usage_in_kb();

$holder = new ProfilerHolder( $profiler );

$b = null;

/**
 * @return string
 */
function make_dummy_data()
{
    return str_repeat( "Hello|", 114242 );
}

$a = make_dummy_data();

$data = explode( '|', $a ); // comment this after narrowing down that a lot of memory is being used here
//$data = array(); // uncomment this and memory usage will drop

$buffer = array();

foreach( $data as $key => $item ){
    $buffer[] = $item;
}

get_usage_in_kb();

unset($a);

get_usage_in_kb();

echo memory_get_peak_usage(TRUE)/1024, ' kb', "n";

$profiler->timerEnd();

unset( $profiler );
xdebug_debug_zval( 'profiler' );

//var_dump( $holder );

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.

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!

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.

Очередная проблема в работе сайта принесла тему для нового поста — ошибка «Fatal error: Allowed memory size of«.  Пришлось оказать помощь товарищу с устранением этой неприятности.

fatal error wordpress

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

Суть такова: в консоли административной панели появляется ошибка:

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 1966080 bytes) in /home/username/public_html/wp-includes/class-simplepie.php on line 5410.

Цифры и путь ошибки могут и будут различаться. Более того, Ваш сайт может не загружаться, а браузер будет писать текст всё той же ошибки и при попытке входа в админку будет все тот же Fatal error.

Причина ошибки одна — CMS употребляет больше оперативной памяти, чем предоставляет хостинг. Чем это вызвано, тоже понятно: однозначно, плагины (изредка проблема возникает после обновления версии движка, но как правило в процессе активации, деактивированных перед обновлением WordPress плагинов).

Как исправить ошибку

А вот путей решения несколько. И один из них точно принесет результат. Также я расскажу как не допустить этой ошибки в будущем. Приступим.

Первый способ

Самый простой, но длительный по времени: написать в техподдержку компании, предоставляющей хостинг. Специалисты все исправят и вы вновь у руля. Однако, может случиться, что это поможет на 3-5 дней (как было у меня) и снова та же ошибка памяти. После 3-х писем в техподдержку мне посоветовали сменить CMS. Но я гордый и начал копать дальше.

Второй способ

Внести в файл .htaccess вашего сайта строку:

php_value memory_limit '64M'

Если файла .htaccess у вашего сайта нет, то сделайте его: берем пустой txt файл (файл блокнота) и вносим туда вышеуказанную строку. Затем переносим это дело с помощью FTP клиента на сервер и там переименовываем в .htaccess. Устанавливаем атрибуты 777, проверяем сработало или нет. Опять же зависит всё от хостинга. Если и это не помогло, то…

Третий способ

Похож на второй, только работаем в другими файлами. Открываете index.php в корне вашего сайта и добавляете в него следующий код:

define(‘WP_MEMORY_LIMIT’, ’64M’);

Разрешенный объем оперативки для сайта вырастет до 64 мегабайт. Для WordPress сайта этот же код вставьте в файл конфигурации wp-config.php. Если хостинг провайдер не выключил в настройках сервера поддержку ini_set, то проблема должна решиться.

Четвертый способ — лучший

Гарантировано избавит вас от ошибки, так как решает саму причину ошибки. Но, возможно, придется пожертвовать плагином. Заходим в админку вкладка «плагины» и начинаем по очереди их деактивировать, проверяя при этом, после каждой деактивации наличие ошибки. Плагин-проказник обязательно найдется, после этого активируйте все плагины, которые не вызывают ошибку.

Если сайт полностью лежит и нет возможности делать манипуляции с админкой, то зайдите на хостинг. Откройте папку wp-content/plugins, скопируйте все плагины к себе на компьютер и поочередно удаляйте один за другим, проверяя — заработал ли сайт.

Кстати, такое решение лечит и другие ошибки.

Если плагин очень нужный и полезный, то следует поиграть версиями: попробовать более свежий или наоборот, более старый. Или найдите аналог. В любом случае нужно придти к консенсусу.

Профилактика ошибок памяти

Что для этого нужно? Ответ прост: постоянно видеть сколько памяти потребляет WordPress. Для этого придется покопаться в коде шаблона. Можно это сделать прямо из админки, раздел «Внешний вид» — «Редактор» — выбрать файл functions.php или через файловый менеджер по адресу …/wp-content/themes/ваша тема/functions.php (открыть с помощью Notepad++ или подобной программой). Перед закрывающим тегом ?> вставляем в файл код:

function usage () {printf (('%d / %s'), get_num_queries (), timer_stop (0, 3));
if ( function_exists ('memory_get_usage') ) echo ' / ' . round (memory_get_usage ()/1024/1024, 2) . 'mb '; }
add_action ('admin_footer_text', 'usage');

Данная функция будет выводить в футере администраторской панели WordPress информацию об объеме потребляемой сайтом памяти. В качестве бонуса вы увидите скорость загрузки страниц и количество запросов к базе данных.

Теперь Вы наглядно контролируйте изменение потребляемой памяти при активации того или иного плагина и сразу увидите, если что-то пойдет не так.

Удачи на вашей охоте за прибылью!

Карта Tinkoff Black

Понравилась статья? Поделить с друзьями:
  • Mysql failed error your password does not satisfy the current policy requirements
  • Mysql error что это значит на сайте
  • Mysql error вывод
  • Mysql error you have an error in your sql syntax error
  • Mysql error while reading greeting packet