Php увеличить размер загружаемого файла
По умолчанию 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 .
Заключение
Мы рассмотрели все способы решения данной проблемы. Наслаждайтесь возможностью загружать большие файлы и продолжайте использовать на своем сайте плагины WordPress . Внесенные в php memory limit htaccess изменения должны вступить в силу через несколько минут, после чего можно будет приступить к работе с новыми параметрами.
Если нужно загрузить большие файлы только один раз, попробуйте сделать это через FTP . Обычно файлы, загруженные через FTP в каталог /wp-content/uploads/ , не отображаются в библиотеке медиа. Но с помощью плагина Media from FTP можно отобразить их всего в несколько кликов.
Если ни один из вариантов не дал результата, свяжитесь со своим хостинг-провайдером.
Дайте знать, что вы думаете по этой теме в комментариях. За комментарии, лайки, дизлайки, подписки, отклики огромное вам спасибо!
Пожалуйста, оставляйте свои отзывы по текущей теме статьи. Мы очень благодарим вас за ваши комментарии, отклики, лайки, подписки, дизлайки!
I'm trying to upload a file larger than 2GB to a local PHP 5.3.4 server. I've set the following server variables:
However, in the error_log I found:
PHP Warning: POST Content-Length of 2120909412 bytes exceeds the limit of 1073741824 bytes in Unknown on line 0
Can anyone tell me why this keeps failing please?
Why are you wanting to use PHP for this instead of something like FTP or any number or other ways of uploading files
Basically I'm using some software written in Adobe AIR to upload a file. AIR is sending the file to the PHP server which uploads and allocates the file to a record. Is there no way to achieve this in PHP?
@Thanatos: Yeah I can see the variables in phpinfo() and they are correct. If I set the limit to >10G, the error states the limit is a negative number instead.
WHM/cPanel
Webuzo
1. Необходимо зайти в раздел Enduser Panel и перейти в меню Configuration > PHP.
2. Редактируем значения параметров post_max_size и upload_max_filesize, после чего сохраняем изменения, нажав кнопку «Save».
6 Answers 6
I had a similar problem, but my config was:
and yet I could not upload a 1.2GB file. The error was very same:
I spent a day wondering where the heck was this "limit of 1073741824" coming from!
Solution:
Actually, the error was in the php.ini parser: It only understands INTEGER numbers, so essentially it was parsing 1.8G as 1G !!
Changing the value to e.g. 1800M fixed it.
Pls ensure to restart the apache server with the below command service apache2 restart
I've been hours trying to find out what could be the issue with a owncloud install for uploading big files, and this was the issue after all.
I don't know about in 5.3.x, but in 5.2.x there are some int/long issues in the PHP code. even if you're on a 64-bit system and have a version of PHP compiled with 64-bit, there are several problems.
First, the code that converts post_max_size and others from ascii to integer stores the value in an int, so it converting "9G" and putting the result into this int will bork the value because 9G is a larger number than a 32-bit variable can hold.
But there are also several other areas of PHP code that are used with the Apache module, CGI, etc. that need to be changed from int to long.
So. for this to work, you need to edit the PHP code and compile it by hand (make sure you compile it as 64-bit). here's a link to a list of diffs:
The file above is a diff on 5.2.10 code, but I just made the changes by hand to 5.2.17 code and i just uploaded a 3.4gb single file through apache/php (which hadn't worked before the change).
I have a website hosted on a PC I have no access to. I have an upload form allowing people to upload mp3 files up to 30MB big. My server side script is done in PHP.
Every time I try and upload a file, I receive an error claiming that the file exceeds the maximum size allowed, so I need to increase the size. My research on the web suggested changing the .htaccess file which I do not have access to, so that won't work. Others suggested that I should add a custom php.ini file to my root which did not work. Any other suggestions?
Конфигурационный файл php.ini
Если у вас есть доступ к файлу php.ini на сервере где расположен сайт, то можно изменить значения upload_max_filesize и post_max_size
PHP функция ini_set()
Ограничение на уровне сайта или веб-приложения обычно дается в файлах php путем изменения директив upload_max_filesize и post_max_size через функцию ini_set():
Обновление файла php.ini
Если вы используете CPanel , перейдите в раздел « Файлы » и нажмите кнопку « Диспетчер файлов ». Убедитесь, что установлен флажок « Показать скрытые файлы », а затем нажмите на кнопку « Перейти ».
Выберите папку wp-admin и найдите файл php.ini или php5.ini . Если такого файла нет, создайте его, нажав на кнопку « Создать файл », расположенную в верхнем левом углу. Назовите файл php.ini и нажмите во всплывающем окне кнопку « Создать файл »:
Если ошибка не исчезла, попробуйте переименовать файл в php5.ini . Когда файл будет открыт, добавьте в него приведенные ниже строки, а затем сохраните изменения и закройте файл:
M - означает мегабайты. Измените лимиты 1000M, 2000M и 3000M на значения, которые необходимы. Изменение значения max_execution_time ограничит время загрузки скрипта.
Во многих случаях используемые значения должны увеличиваться по мере перехода в списке от первой до третьей строки. Upload_max_filesize должен быть самым маленьким, memory limit php ini - самым большим. При этом post_max_size должен иметь среднее значение.
Прежде чем проверить, не исчезла ли ошибка, очистите кэш браузера.
Ngnix client_max_body_size
22 Answers 22
You need to set the value of upload_max_filesize and post_max_size in your php.ini :
If you can't change your php.ini , you're out of luck. You cannot change these values at run-time; uploads of file larger than the value specified in php.ini will have failed by the time execution reaches your call to ini_set .
On Linux, it's usually in /etc/php/ or something along those lines. If you're on a shared server, you're out of luck unless your hosting provider is generous enough to provide a per-user php.ini file.
If your using WAMP under windows, you can edit it by clicking the WAMP icon > PHP -> php.ini. In Debian, my config file is in /etc/php5/apache2.
I suggest setting a higher size on post_max_size . The overall size of the posted fields may be higher than the filesize, so if you are having the edge case of someone uploading a 40MB file it will fail due to exceeded post_max_size .
You can change it via an .htaccess file.
.htaccess files are stored in the same directory as your .php files are. They modify configuration for that folder and all sub-folders. You simply use them by creating an .htaccess file in the directory of your choice (or modify it if present).
The following should enable you to increase your upload limit (if the server provider allows PHP config changes via .htaccess ).
It seems that it doesn't always work. On my dev machines setting appropriate value in .htaccess did the job. On the shared hosting however this setting do not work however error message is showing that maximum allowed upload size is that value I set in .htaccess. So a very wierd situation happens.
Looks like adding this in the .htaccess only works if you are running Apache. Try it and works fine for me.
This doesn't work if these 2 lines in php.ini were uncommented:; Name for user-defined php.ini (.htaccess) files. Default is ".user.ini" ;user_ini.filename = ".user.ini" ; To disable this feature set this option to empty value ;user_ini.filename =
Worth noting that if you're using apache CGI or Fast CGI this will cause 500 errors. Wrap this inside
and it worked great for me!
You can also use ini_set function (only for PHP version below 5.3):
Like @acme said, in php 5.3 and above this settings are PHP_INI_PERDIR directives so they can't be set using ini_set. You can use user.ini instead.
In recent PHP versions these ini-settings are PHP_INI_PERDIR only, so you can't set them in your script. See here for more details.
To locate the ini file, first run
Then open the file and change
replacing the 2M with the size you want, for instance 100M.
It shows the file as /etc/php5/cli/php.ini but my config file is /etc/php5/apache2/php.ini . Some kind of misleading.
There are 2 php.ini files. and with that command in answer, it shows you which one are you using! So There you need to make changes in order to take effect!
How would that be true @lewis4u, if the server runs in fpm? What you are using in the server and on the command line are different things. The real php.ini is what a phpinfo() call on the server will show. As the CLI process lives only for one command, I don't see how the php.ini in cli would take precedence to fpm. It's possible this was different in 2017, but I think that' unlikely. Please correct me, if I'm wrong, anybody.
I have the same problem in the past .. and i fixed it through .htaccess file
When you make change on php configration through .htaccess you should put configrations in IfModule tag, other that the Internal server error will arise.
This is an example, it works fine for me:
this is a very important remark wiithout wrapping it in ifmodule with specifying your php version it wont work !!
This is the solution for me. Just works fine. If you are using a framework like codeignitor, ".user.ini" needs to be in the same place as index.php
Thanks. That's works for me. This is ideal for shared hosting, where you do not have access to php.ini. I would just add that it is available since PHP 5.3
the answers are a bit incomplete, 3 things you have to do
in php.ini of your php installation (note: depending if you want it for CLI, apache, or nginx, find the right php.ini to manipulate. For nginx it is usually located in /etc/php/7.1/fpm where 7.1 depends on your version. For apache usually /etc/php/7.1/apache2 )
or set other values. Restart/reload apache if you have apache installed or php-fpm for nginx if you use nginx.
many times i have noticed that site wit shared hosting do not allow to change settings in php.ini files. one also can not even crate .htaaccess file at all. in such situation one can try following things
Thank you I forgot the name of the timeouts so this is the right answer because even if you increase max upload size the process can still time out.
I modded probably four other php.ini files, including the one my system called the "Loaded Configuration File" ( php -i | grep -i "loaded configuration file" ) and the one found on the info.php page but none of them helped. The key to discovering the correct path was found on a site from 2012. They said the path "/etc/php5/apache2/php.ini" was deprecated even BACK THEN but it gave me a clue where to find it. For PHP7 it's a little different than in PHP5 but the concept is the same.
Maybe this will help some otherwise helpless schmuck like myself.
That being said, the answer to the OP in my case would be that someone with admin privileges on the box would have to do it.
EDIT: the full text of my note to myself:
In order to change the max upload size, edit upload_max_filesize and [if needed?] post_max_size in /etc/php/7.0/apache2/php.ini (or in older versions: /etc/php5/apache2/php.ini )
/etc/init.d/apache2 restart
EDIT AGAIN: since you're importing big files you may need to change the timeout for processing them. In my case, the file named, "config.default.php" was found at /usr/share/phpmyadmin/libraries/config.default.php with the variable $cfg['ExecTimeLimit'] = 300; I changed mine to 900 for a huge import, for instance. Afterward you need to restart apache
I had the same problem. I have tried three ways that were usually suggested:
- functions.php
- php.ini
- .htaccess
none if which solved my problem. I am using godaddy and came across a suggested solution which was:
- got to Web Hosting, then Manage
- Under Software select Select PHP version
- Select Switch to PHP Options found on the top right corner of the table in font color: blue
- On the bottom most part, you'll probably have upload_max_filesize = 2M
- Now, feel free to change it
- Be sure to click the Save button!
- Now go to your wp-admin panel, select Media then Add
Voila! Now you have a different max upload file size :)
Well, I would like to add my 2 cents here.
I'm using shared webhosting and I tackled this problem many times, tried to resolve it on my own but to no avail. Finally I managed to resolve it through checking various web sources and contacting my hosting service provider. My questions were "How can I change php value memory_limit in shared webhosting?", "How can I change php value upload_max_filesize in shared webhosting?", "How can I change php value max_input_vars in shared webhosting?", "How can I change php value max_execution_time in shared webhosting?", "How can I change php value max_input_time in shared webhosting?" and many more by configuring or changing php.ini or .htaccess file. I tried to change them but problems arose. Finally I contacted my hosting provider, and it turns out that I set my php to native, they changed it to php 5.6, here is their answer:
"Your PHP was set to 'native' mode which means you can't override those values. I've changed you to just '5.6' so you should be good to go."
After that I connected my website through ftp Filezilla, also don't forget to make both your ftp service to show hidden files, and your local computer to do so, because .htaccess file was hidden in my local laptop and in my website. It was available in public_html folder, I just downloaded it and added the following codes to the end of the file and then uploaded it back to the server:
Everything is working properly for the time being, if any of you overcome with some problems please write here and warn me so that I can change the above-shown codes. By the way, I also upload some pictures which shows the change.
One more thing I almost forgot to mention ZipArchive installation on your shared webhosting service, I managed that requirement to tick by just going to php settings through my cpanel, click on php selector extensions and then tick zip section, that's all.
PS: I'm open to good practices, and if you see any bad practice here please let me know, I'll try to change them. Thanks.
Вы разработчик PHP или системный администратор, управляющий серверами, на которых размещаются PHP-приложения?
Если да, то следуйте по этой статье, в которой показано, как увеличить размер загрузки файлов в PHP, а также объясню некоторые основные директивы PHP для обработки загрузки файлов, а также данные POST.
По умолчанию размер загрузки файлов PHP установлен на максимальный 2 МБ-файл на сервере, но вы можете увеличить или уменьшить максимальный размер загрузки файла с помощью файла конфигурации PHP (php.ini), этот файл можно найти в разных местах на разных распределения Linux.
Чтобы увеличить размер загрузки файлов в PHP, вам необходимо изменить переменные upload_max_filesize и post_max_size в файле php.ini.
Кроме того, вы также можете установить максимальное количество файлов, которые могут быть загружены одновременно, в одном запросе, используя max_file_uploads.
Обратите внимание, что из PHP 5.3.4 и более поздних версий любые поля загрузки, оставленные пустыми при представлении, не учитываются в этом пределе.
Переменная post_max_size, которая используется для установки максимального размера данных POST, которые PHP примет.
Установка значения 0 отключает ограничение.
Если чтение данных POST отключено с помощью enable_post_data_reading, оно игнорируется.
После внесения вышеуказанных изменений сохраните измененный файл php.ini и перезапустите веб-сервер, используя следующие команды в ваших соответствующих дистрибутивах Linux.
Файл .htaccess
Если вы используете веб-сервер Apache, то можете через файл .htaccess увеличить значения upload_max_filesize и post_max_size:
DirectAdmin
В контрольной панели DirectAdmin отсутствует возможность редактирования размера загружаемого файла в веб интерфейсе. Для КП DirectAdmin производить настройки необходимо с помощью ssh либо sftp протокола по инструкции выше.
Однако в DirectAdmin существует возможность конфигурирования файла php.ini для каждого пользователя в отдельности. Будут приведены примеры команд, которые необходимо выполнять при подключении к ВПС по SSH.
Для этого необходимо:
Создать директорию
Войти под пользователем root. Необходимо создать директорию php в /usr/local/directadmin/data/users/user/:
и положить в нее файл php.ini:
Путь к файлу php.ini, будет иметь такой вид:
В секции, где описан пользователь user, нужно добавить такую строчку:
Перезапуск Apache
Для применения настроек необходим перезапуск Apache:
Также есть возможность перечитать директивы без перезапуска веб-сервера:
Изменение файла wp-config.php
Если оба способа не дали результата, попробуйте отредактировать файл wp-config.php , добавив следующий код в самый низ, перед строкой " happy blogging ":
Сохраните файл и очистите кэш браузера.
Как увеличить размер загрузки файлов в PHP
Чтобы увеличить размер загрузки файлов в PHP, вам необходимо изменить переменные upload_max_filesize и post_max_size в файле php.ini.
Кроме того, вы также можете установить максимальное количество файлов, которые могут быть загружены одновременно, в одном запросе, используя max_file_uploads.
Обратите внимание, что из PHP 5.3.4 и более поздних версий любые поля загрузки, оставленные пустыми при представлении, не учитываются в этом пределе.
Переменная post_max_size, которая используется для установки максимального размера данных POST, которые PHP примет.
Установка значения 0 отключает ограничение.
Если чтение данных POST отключено с помощью enable_post_data_reading, оно игнорируется.
Директивы upload_max_filesize и post_max_size
Директива upload_max_filesize определяет максимальный размер загружаемых файлов на сервер.
Директива post_max_size определяет максимальный размер POST запросов при отправке файлов с форм. Его значение должно быть больше или равно максимальному размеру загружаемых файлов.
Автор
Программист с образованием в области IT и опытом разработки на разных языках. Автор статей по программированию. Общий опыт работы в сфере IT и интернета более 5 лет.
Изменение лимитов в WHM
Если сайт размещен на VPS или выделенном сервере, можно попробовать изменить лимиты в WHM .
После того, как вы вошли в систему, перейдите в раздел Конфигурация сервера> Настройки > PHP .
Введите нужные вам значения и нажмите кнопку « Сохранить ».
Затем перейдите в раздел Конфигурация служб> Редактор конфигурации PHP . Прокрутите страницу вниз до разделов memory_limit и upload_max_filesize :
Введите необходимые значения. В разделе « Параметры и информация » найдите memory_limit и задайте то же значение, которое вы установили в memory limit php ini и .htaccess .
Настройка с помощью SSH/SFTP
Обратите внимание, параметр upload_max_filesize не должен быть больше post_max_size, что позволит лучше обрабатывать Ваши запросы на загрузку файлов.
После редактирования php.ini необходимо перезапустить веб-сервер.
Для этого выполните команду от имени root пользователя :
Проверяем максимальный размер загружаемого файла:
ISPManager
При использовании контрольной панели ISP manager, Вам необходимо выполнить следующие действия:
- Войти под пользователем root.
- Настройки web-сервера -> PHP -> Выбрать версию PHP -> Настройка
Добавить комментарий Отменить ответ
Эта простая однострочная программа для Powershell выведет текущее время работы вашего компьютера. Вывод показан в несколько столбцов, но может быть выведен и в одну строку. PS C:\Users\Windows 11> (get-date) - (gcim Win32_OperatingSystem).LastBootUpTime Days : 0 Hours : 0 Minutes : 41 Seconds : 27 Milliseconds : 915 Ticks : 24879150105 TotalDays : 0.0287953126215278.
Ошибка 504 gateway time-out возникает тогда, когда Nginx не может получить ответ от службы достаточно долго. Например, от PHP-FPM. Nginx и PHP-FPM Наиболее распространенной причиной этой ошибки является совместная работа Nginx и PHP-FPM. В случае очень медленных PHP-скриптов Nginx выдает тайм-аут шлюза 504, когда не ожидает ответа в течение 30 секунд (по умолчанию). Чтобы избавиться.
17 сентября 2021 года произошло событие, всколыхнувшее кинематографический мир. На платформе Netflix появился корейский сериал “Игра в кальмара”. Всего пары недель ему хватило для того, чтобы выйти на первые позиции по популярности не только на Родине, но и в Соединенных Штатах, России. Оценить сюжет сериал можно не только просмотром, но и игрой squid game challenge скачать которую.
Данная статья посвящена настройке максимального размера файла в PHPMyAdmin и максимальному размеру php-запроса, обрабатываемого интерпретатором, на OpenVZ VPS и KVM VPS. Как многим известно, СУБД PHPMyAdmin написана на языке PHP, поэтому мы будем производить изменения в конфигурационных файлах интерпретатора PHP.
Редактирование файла .htaccess
Если редактирование php.ini не помогло, попробуйте изменить файл .htaccess . Добавьте приведенный ниже код в конец файла:
Измените значения php ini set memory limit так, как вам нужно. Не забудьте сохранить файл и очистить кэш браузера.
Как увеличить максимальный размер загружаемых файлов PHP
Если вы столкнулись с тем, что при загрузке файла большого размера через PHP у вас не получается его загрузить и форма сбрасывает отправку, то это говорит о том, что настройки сервера, где расположен сайт, позволяют загружать файлы только до установленного размера. Но это не беда, ведь данный лимит можно увеличить.
Лимит на загрузку может быть установлен в нескольких местах с помощью специальных директив.
Содержание
Читайте также: