- php memory limit или как увеличить лимиты на размер загружаемых файлов и объем выделяемой памяти
- Обновление файла php.ini
- Редактирование файла .htaccess
- Изменение файла wp-config.php
- Изменение лимитов в WHM
- Заключение
- PHP Form Submission Limits
- Finding the Current Directive Values
- Changing Maximum Post Size
- Changing Maximum Number of Form fields
- Changing Maximum File Upload Size
- Changing PHP Execution Timeout Period
- Changing Maximum Data Parsing Timeout Period
- Changing the Memory Limit
- Test Your Site and Your Form!
php memory limit или как увеличить лимиты на размер загружаемых файлов и объем выделяемой памяти
По умолчанию WordPress устанавливает небольшой лимит на размер загружаемых изображений, видеороликов и других файлов. Аналогичная ситуация с PHP memory limit , который сказывается на возможности запускать плагины и скрипты.
Если вы запускаете сайт с большим количеством контента, эти лимиты могут стать проблемой. Можно получить ошибку при загрузке:
Объем загружаемого файла превышает ограничение, заданное директивой upload_max_filesize в файле php.ini
Если достигнут предел выделяемой памяти, то выведется другое сообщение об ошибке:
Неустранимая ошибка: допустимый размер памяти 12345678 байт исчерпан (вы пытались выделить 2345678 байт) в /home/your-username/public_html/wp-includes/plugin.php в строке 1000
Рассмотрим наиболее эффективные способы увеличения этих лимитов на сервере. Начнем с memory limit php ini .
Обновление файла php.ini
Если вы используете CPanel , перейдите в раздел « Файлы » и нажмите кнопку « Диспетчер файлов ». Убедитесь, что установлен флажок « Показать скрытые файлы », а затем нажмите на кнопку « Перейти ».
Выберите папку wp-admin и найдите файл php.ini или php5.ini . Если такого файла нет, создайте его, нажав на кнопку « Создать файл », расположенную в верхнем левом углу. Назовите файл php.ini и нажмите во всплывающем окне кнопку « Создать файл »:
Если ошибка не исчезла, попробуйте переименовать файл в php5.ini . Когда файл будет открыт, добавьте в него приведенные ниже строки, а затем сохраните изменения и закройте файл:
upload_max_filesize = 1000M post_max_size = 2000M memory_limit = 3000M file_uploads = On max_execution_time = 180
M — означает мегабайты. Измените лимиты 1000M, 2000M и 3000M на значения, которые необходимы. Изменение значения max_execution_time ограничит время загрузки скрипта.
Во многих случаях используемые значения должны увеличиваться по мере перехода в списке от первой до третьей строки. Upload_max_filesize должен быть самым маленьким, memory limit php ini — самым большим. При этом post_max_size должен иметь среднее значение.
Прежде чем проверить, не исчезла ли ошибка, очистите кэш браузера.
Редактирование файла .htaccess
Если редактирование php.ini не помогло, попробуйте изменить файл .htaccess . Добавьте приведенный ниже код в конец файла:
php_value upload_max_filesize 1000M php_value post_max_size 2000M php_value memory_limit 3000M php_value max_execution_time 180 php_value max_input_time 180
Измените значения php ini set memory limit так, как вам нужно. Не забудьте сохранить файл и очистить кэш браузера.
Изменение файла wp-config.php
Если оба способа не дали результата, попробуйте отредактировать файл wp-config.php , добавив следующий код в самый низ, перед строкой » happy blogging «:
Сохраните файл и очистите кэш браузера.
Изменение лимитов в WHM
Если сайт размещен на VPS или выделенном сервере, можно попробовать изменить лимиты в WHM .
После того, как вы вошли в систему, перейдите в раздел Конфигурация сервера> Настройки > PHP .
Введите нужные вам значения и нажмите кнопку « Сохранить ».
Затем перейдите в раздел Конфигурация служб> Редактор конфигурации PHP . Прокрутите страницу вниз до разделов memory_limit и upload_max_filesize :
Введите необходимые значения. В разделе « Параметры и информация » найдите memory_limit и задайте то же значение, которое вы установили в memory limit php ini и .htaccess .
Нажмите кнопку « Сохранить » и очистите кэш браузера.
Заключение
Мы рассмотрели все способы решения данной проблемы. Наслаждайтесь возможностью загружать большие файлы и продолжайте использовать на своем сайте плагины WordPress . Внесенные в php memory limit htaccess изменения должны вступить в силу через несколько минут, после чего можно будет приступить к работе с новыми параметрами.
Если нужно загрузить большие файлы только один раз, попробуйте сделать это через FTP . Обычно файлы, загруженные через FTP в каталог /wp-content/uploads/ , не отображаются в библиотеке медиа. Но с помощью плагина Media from FTP можно отобразить их всего в несколько кликов.
Если ни один из вариантов не дал результата, свяжитесь со своим хостинг-провайдером.
PHP Form Submission Limits
A short time ago, a client’s form wouldn’t process the way I thought it should.
I had the hardest time finding the bug (I thought it was a bug). I ended up with debugging lines for virtually every line of the form processing software.
The issue was that not all the form fields were arriving. I checked the form tag’s enctype and accept-charset attributes and checked that all HTML tags were properly closed and I could see nothing wrong. Yet, it seemed that not all the form fields got submitted.
Finally, after sitting back, eyes closed, thinking this thing through, my thought turned to the sheer number of form fields the form was submitting — well over a thousand.
It couldn’t be the byte size of the submission. I had changed that to a higher number for the client only a short time ago. But I checked PHP documentation anyway for inspiration.
PHP was limiting the number of form fields that could be submitted to 1000. When I made that number higher, the form worked like it should.
So it wasn’t a bug in my code at all, just a PHP limitation.
Therefore this article: To let you know there are some form use limits imposed by PHP that could have you looking for a bug where no bugs exist.
Examples: (1) A form submits OK, but not all the form information arrives at the destination. (2) Some files upload OK and others don’t.
Of course, there could be a bug where your instincts say there’s likely to be one. I’m not saying otherwise. But what I am saying is there may be a reason that’s not in your code — a PHP limitation reached.
Unless your hosting company has configured your account otherwise, you’re able to change some form-related PHP configurations with the .htaccess file. I’ll describe them in a moment.
But first, before you go changing a PHP directive, have a look at the current value. If your form has only 3 fields and the PHP directive allows 1000 fields, then the issue with your form isn’t that particular directive.
Finding the Current Directive Values
The way to view the values of the current directive is to create a PHP page with this one line:
Name the page info.php and upload it to your server. (If you use a different file name, translate the following instructions accordingly.)
Type the URL of info.php into your browser.
All the directives discussed in this article are in the «Core» section of the report you’ll see in your browser window.
The Core section has a table with three columns: Directive, Local Value, and Master Value.
Find the directive you’re interested in. In the Local Value column is the current value, the value that may be changed in the .htaccess file. In the Master Value column is the value as specified in the PHP .ini file.
The Master Value column has the default value.
The Local Value column has the same value as the Master Value column unless the Local Value has been changed.
When the value in the Local Value column is changed with an .htaccess file, the change affects only PHP software running in the directory where the .htaccess file is located, and the directory’s subdirectories.
Thus, you can limit the change to certain directories. Or you can have it affect all public directories by making the .htaccess change in the document root directory.
Changing Maximum Post Size
If your form has text boxes that may contain very large amounts of text or file upload fields that may upload large files, your form may exceed the post size limit. Some or all of the form submission would fail to arrive at the PHP script.
To change the limit, put this line into the .htaccess file (customization note follows):
php_value post_max_size 20M
Change the 20M value to the maximum number of megabytes the form may submit followed by the letter «M» (so PHP converts the number to megabytes).
Reload info.php in your browser and verify the Local Value has changed.
Changing Maximum Number of Form fields
If your form contains many, MANY form fields, the number of fields may exceed the maximum the PHP configuration allows. This would cause some of the field information to never arrive from the form to the PHP script.
(This happening to me is what prompted this article.)
To change the limit, put this line into the .htaccess file (customization note follows):
php_value max_input_vars 1000
You have the information at hand to change 6 PHP directives that can limit form functionality.
Change the 1000 value to the maximum number of fields that forms may submit.
Reload info.php in your browser and verify the Local Value has changed.
Changing Maximum File Upload Size
If your form contains file upload fields and uploaded files exceed the file upload size limit, some or all of the uploads may never arrive or arrive corrupted.
To change the limit, put this line into the .htaccess file (customization note follows):
php_value upload_max_filesize 20M
Change the 20M value to the maximum number of megabytes for uploaded files followed by the letter «M» (so PHP converts the number to megabytes).
The Maximum Post Size (post_max_size) value should be larger than the maximum for uploaded files. Otherwise, any other information accompanying the file upload could be lost.
As with all changes of this type, reload info.php in your browser to verify the Local Value has changed.
Changing PHP Execution Timeout Period
If your PHP script takes a long time to process form submissions, it may time out. When the script times out, it quits and nothing else gets done with the form content.
(This directive helps prevent poorly-written scripts from tying up the server. If you change it, it’s prudent to make the number not much higher than you really need it to be.)
To change the limit, put this line into the .htaccess file (customization note follows):
php_value max_execution_time 30
Change the 30 value to the maximum number of seconds the script may run before it times out.
Use info.php to verify the Local Value has changed.
Changing Maximum Data Parsing Timeout Period
If your form contains complex fields that need a lot of time to parse the POST or GET input data, the parsing period may time out and the script stop running. In that case, nothing further is done with the submitted data.
To change the limit, put this line into the .htaccess file (customization note follows):
php_value max_input_time 30
Change the 30 value to the maximum number of seconds PHP scripts may spend on parsing input data.
Verify the Local Value has changed with your info.php page.
Changing the Memory Limit
If your form contains data or requires data processing that takes a lot of memory, it may exceed the memory limit. The result can be anything from corrupted data to the PHP script stopping altogether.
To change the limit, put this line into the .htaccess file (customization note follows):
php_value memory_limit 128M
Change the 128M value to the maximum number of megabytes of memory the PHP script may use followed by the letter «M» (so PHP converts the number to megabytes).
Generally speaking, the memory limit should be larger than the Maximum Post Size (post_max_size) value.
Reload info.php in your browser and verify the Local Value has changed.
Test Your Site and Your Form!
As with all .htaccess changes, test your site to verify it still works. A typographical error could disable an entire site.
If possible, test .htaccess changes in a test subdirectory before incorporating the changes into a live directory.
After the .htaccess changes mentioned above, test your forms. Just to make sure they still work. A typographical error (3M instead of 300M, for example) could make things worse than they were.
While the PHP configurations generally are sufficient for most forms, some forms can exceed the limits. You have the information at hand to change 6 PHP directives that can limit form functionality.
(This article first appeared in Possibilities ezine.)
Was this article helpful to you?
(anonymous form)