Php memory limit debian

PHP memory_limit – understanding and increasing this setting

PHP memory_limit is per-script, just as a highway’s speed limit is per-vehicle. For example, although PHP’s memory limit may be set high to 1GB, that does not mean that scripts will pile up to use that 1GB. Let’s take a quick look at understanding PHP’s memory_limit setting.

PHP memory_limit is a per-script setting

PHP.net’s documentation puts it this way:

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.

Unlike, say, MySQL’s key_buffer_size or innodb_buffer_pool settings, PHP memory_limit setting is not a storage space where multiple PHP scripts pool from or grow within. Rather it’s a per-script limit. PHP memory_limit is the maximum amount of server memory a single PHP script is allowed to consume. When blocked, the resulting error output looks something like this:

Fatal error: Allowed memory size of x bytes exhausted (tried to allocate x bytes) in /path/to/php/script
PHP Fatal error: Out of memory (allocated x) (tried to allocate x bytes) in /path/to/php/script

So, for example, if two or more scripts are requested simultaneously, each is completely independent of the other. They do not share the memory_limit setting. Remember, PHP is not designed for and does not support multithreading. Thus, if five (5) PHP scripts simultaneously use 100MB each, that would total 500MB of PHP memory usage, and a PHP memory limit of 128M wouldn’t be hit.

Читайте также:  Convert char to int in cpp

That said, for scripts that request other PHP scripts inline using require, include, or include_once, this limit is then inherited and shared by all included scripts that are dependent on the parent script.

“The include statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.” – W3schools.

“The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.” – php.net

PHP memory_limit

PHP memory_limit is per-script, just as a highway’s speed limit is per-vehicle.

Now regarding the original example mentioned at the outset. A lower setting of 128M is always better because if PHP scripts are trying to use more than 128M, those scripts would now return memory limit exceeded errors. In the above issue, that was not the case, so regardless of the 128M or 1G memory_limit setting, it only comes into play if there are inefficient scripts.

Fortunately, the PHP memory_limit setting will block inefficient code, alerting you to optimize your code. Until fixed, you may want to temporarily increase PHP memory_limit to avoid your web application becoming unusable due to PHP out-of-memory errors.

If you don’t have available memory on your server, you’ll sometimes be faced with deciding whether to increase PHP memory_limit to meet the requirements of scripts or to optimize your code. It would be best if you always optimized as the preferred option when possible. Also, you can increase PHP’s memory limit for specific websites. One method would be to place a php.ini file in the site’s webroot. You can even set the limit for specific scriptname.php. For example using ini_set(‘memory_limit’,’256MB’).

How to increase PHP memory_limit

To increase the PHP memory limit setting, edit your PHP.ini file. Increase the default value (example: Maximum amount of memory a script may consume = 128MB) of the PHP memory limit line in php.ini.

Alternatively, you can edit your .htaccess file (Not recommended. See: Apache Performance: Disable .htaccess)

php_value memory_limit 1024M

If you don’t have access to these files or lack the experience to make this change, you can contact your web host and ask them to increase your PHP memory limit.

Originally published: Sep 18th, 2017.
Last updated: February 6th, 2023.

Источник

Как увеличить лимит памяти для PHP более 2 ГБ?

У меня проблема с увеличением предела памяти для PHP как модуля Apache. Если я поместил следующую директиву в конфигурацию Apache, это будет работать нормально:

php_value memory_limit 1.99G 

Но более 2 ГБ не работают, он восстанавливает это значение до 128 МБ. В чем проблема? Мне нужно больше памяти для некоторых задач, связанных с PDF. Сервер — это Debian 2.6.32-5-amd64 # 1 SMP, PHP 5.3.3-7 + squeeze13 с физической памятью 12 ГБ.

Возможно, вам следует оставить конфигурацию apache по умолчанию и ini_set(‘memory_limit’, -1); только на файл вам это нужно. Посмотри, работает ли это.

Использование МБ вместо ГБ ничего не меняет. Я думаю, что есть некоторые другие ограничения, возможно, где-то в конфигурации Apache. Кроме того, насколько я знаю, memory_limit нельзя изменить во время выполнения, и значение по умолчанию составляет 128 МБ. Может быть, я могу установить это в основном php.ini, но я не хочу, чтобы другие VHOST имели такие большие настройки, поэтому я использую его для VHOST.

@mikikg вы не можете привязать настройки php к виртуальному хосту. Как только процесс apache завершит обработку запроса, он может быть использован в любом другом запросе на любом из виртуальных хостов.

@Ray Рей хмм, не понимаю это объяснение? Настройки PHP могут быть изменены для каждого виртуального хоста через конфигурацию apache, я уже использую такие вещи для различных целей.

@mikikg, как только ваш сценарий использует память, пока процесс apache не будет запущен, он сохранит столько памяти. Вы можете установить максимальное количество запросов равным ‘1’, и после каждого запроса дочерний процесс будет умирать, но это настройка сервера Apache, и я бы не советовал делать это.

@Ray Хорошо, пойми это. Хитрость заключается в том, что этот скрипт работал на каком-то более старом сервере Debian, где я увеличивал объем памяти более чем на 2 ГБ, забыв, что именно потому, что старый сервер «ушел с потока» (RAID0 упал!)

Источник

Увеличить лимит памяти PHP (memory limit)

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

Ошибка PHP о недостатке памяти

PHP позволяет использовать стандартный объем памяти. Иногда веб-сайту требуется больше памяти, чем установлено по умолчанию. В этом можно увеличить его, чтобы он соответствовал потребностям вашего сайта.

Также иногда может возникать ошибка, указывающую на то, что лимит памяти достигнут. Она может выглядеть следующим образом:

Fatal error: Allowed memory size of 83260710 bytes exhausted (tried to allocate 4062 bytes)

Увеличение лимита памяти в php.ini

Открываем на редактирование файл php.ini, по умолчанию /etc/php.ini

в секции [PHP] редактируем или добавляем параметр memory_limit

после этого необходимо перезапустить веб-свервер (к примеру apache)

в случае с использование php-fpm требуется перезапустить только его

Увеличение лимита памяти в .htaccess

Apache позволяет передавать параметры php с использованием .htaccess, без необходимости перезапускать сервер.

Для этого в в корне сайта добавляем (желательно как можно ближе к началу) следующий текст

php_value memory_limit 128M

После сохранения изменений настройки вступят в силу.

Увеличение лимита памяти в php скрипте

Изменения лимита памяти возможно так же в самом PHP скрипте. Аналогично в самом начале скрипта добавляем строку

После сохранения изменений, при следующем запуске изменения вступят в силу.

Увеличение лимита памяти в WordPress

При использовании WordPress, настройки в файле php.ini могут не сработать, так как WordPress переопределяет их в файле wp-config.php. Чтобы исправить это, необходимо в файле wp-config.php, указать конкретный лимит памяти. Например:

define( 'WP_MEMORY_LIMIT', '128M' ); define( 'WP_MAX_MEMORY_LIMIT', '128M' ); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php');

Источник

Оцените статью