Php не загружаются файлы php ini
php -i | grep -i "upload\_max\_filesize\|post\_max\_size\|max\_file\_uploads" is a helpful command that can help you catch that maybe whatever "ini" file you updated either hasn't been reloaded or might not be the correct file in use at all.
Решение
Где установлен PHP C:\php Eсть php.ini-development а также php.ini-production , Вы можете скопировать или переименовать один из них в php.ini , Это шаблоны, которые имеют все необходимые настройки по умолчанию. Основное отличие состоит в том, что при разработке будет включена отчетность об ошибках, а при производстве:
Он должен быть загружен из любого каталога PHP C:\php или же C:\windows , Я использую каталог PHP, так как PHP, я считаю, всегда будет искать в каталоге, из которого запускается PHP:
15 Answers 15
I had a fix for PHP-FPM 7.1
Edit your php.ini in
Make changes to whatever option you want like, post_max_size, upload_max_filesize, max_execution_time & so.
save & close file.
sudo service php7.1-fpm restart
For me, it was this simple - and it's logical. We have changed PHP variables, not Apache2. So restarting PHP is all that was needed!
I had an other fix for it. os: ubuntu 16.04 phpversion: 7.0
I created a phpinfo.php file containing:
Navigating to it and lookup the line:
Loaded Configuration File : /etc/php/7.0/cgi/php.ini
Now you know what php.ini file is loaded.
ssh into the server and use your favorite editing tool (mine is nano) to adjust the php.ini
change the values to meet your preferences.
post_max_size = 128M
upload_max_filesize = 64M
Save and close the file.
check the phpinfo.ini if the new values are as set.
and if they do you are set to go.
/etc/php/7.0/cgi/php.ini should be /etc/php/7.0/cli/php.ini . There is no cgi dir in default php installation
in my loaded php.ini config , my error_reporting values is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED -> this is wrong!, so i changed it to
error_reporting: E_ALL and then restart apache2 server, now everything working fine !
so please note : if php.ini have any error , it will use default value (which means upload_max_filesize always 2M )
@CuongDC thank you but I still need to see my errors, how can I do that? I still get 2M though I changed my value
Ubuntu php-fpm located at /etc/php/7.2/fpm so
- cd /etc/php/7.2/fpm
- sudo nano php.ini
- Search for post_max_size = 512M and add your fav size that you really needed
- Search for upload_max_filesize = 512M and add your fav size that you really needed
- Save File
- And Last DO NOT FORGET TO RESTART PHP7.2-FPM to restart sudo service php7.2-fpm restart
I also found that restarting the httpd service didn't pick up changes in the loaded configuration file ( /etc/php.ini on Fedora 29). It's worth listing all systemd units and doing a grep for the string "php":
Restarting php-fpm did the trick for me:
I am using Nginx and my solution was to restart php-fpm.
Restarting Nginx didn't do anything.
This worked for me! Thank you! I'm using apache and recently moved to php-fpm - I had no idea it was a separate service!
i also had this problem!
if you are using php-fpm service need to find php-fpm.conf and add line
for changing other type of values
Most people are forgetting to restart their php via the terminal that's why it isn't working, if you think you've done everything correctly be sure to restart your php & the server.
Yeah, Actually I forgot to restart correctly.
sudo service apache2 restart is not enough
And then use following command to restart the php server:
Now you should be able to see the changes of upload size. Cheers !
as shown in here you can get to know more about the php server controlls :
Опция MAX_FILE_SIZE не должна позволять передачу файлов, размер которых превышает лимит, установленный конфигурационной директивой upload_max_filesize в php.ini . Ограничение по умолчанию составляет 2 мегабайта.
В случае, если установлены ограничения памяти, вам может понадобиться увеличить значение опции memory_limit. Убедитесь в том, что значение memory_limit достаточно велико.
В случае, если опция max_execution_time установлена слишком маленьким значением, необходимое время работы скрипта может превышать это значение. Убедитесь в том, что значение max_execution_time достаточно велико.
Замечание: Директива max_execution_time касается исключительно времени, используемого непосредственно самим скриптом. Время, потраченное на внешние действия, такие как системные вызовы при помощи функции system() или sleep() , обращения к базе данных, а также время, потраченное на загрузку файла и другие действия, происходящие вне скрипта, не учитываются при определении максимально допустимого промежутка времени, отведённого для выполнения скрипта.
Директива max_input_time указывает максимально допустимое время в секундах для получения входящих данных, в том числе и загружаемых файлов. В случае, если вы имеете дело с несколькими или большими файлами, либо удалённые пользователи используют медленный канал, ограничение по умолчанию в 60 секунд может быть превышено.
Если директива post_max_size слишком мала, большие файлы не смогут быть загружены на сервер. Убедитесь, что значение директивы post_max_size достаточно велико.
Опция max_file_uploads контролирует максимальное количество загружаемых файлов в течение одного запроса. Если загружается большее количество файлов, чем указано в этом ограничении, то массив $_FILES прекратит дальнейшую обработку файлов по достижении этого ограничения. Например, если max_file_uploads установлено в 10 , то $_FILES никогда не будет содержать больше 10 элементов.
Если не проверять, с какими файлами вы работаете, пользователи могут получить доступ к конфиденциальной информации, расположенной в других директориях.
Поскольку разные системы по-разному работают с файловой структурой, нет никаких гарантий того, что файлы с экзотическими именами (например, которые содержат пробельные символы) будут обработаны корректно.
Разработчики не должны использовать одинаковые имена для обычных полей ввода (тег input ) и полей выбора файла в пределах одной и той же формы (например, используя имя для тега input наподобие foo[] ).
$_FILES and $_POST will return empty
We use this function to handle file uploads.
Since $_FILES allows for more than a single file, this loops through each file and if there's an error, it is displayed in human readable language to the error log and then returned / exited. You can adjust that to echo's if preferred:
error_log("======================================= $messageBefore");
error_log("======================================= cmmediabrowsedfor"]["tmp_name"][0]) || !is_uploaded_file($_FILES["cmmediabrowsedfor"]["tmp_name"][0])) error_log("NO FILE GOT UPLOADED ");
> else error_log("SUCCESS FILE GOT UPLOADED ");
>
>
Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code:
PHP has the somewhat strange feature of checking multiple "maximum file sizes".
The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received.
In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.
One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space. Even though "no error" is 0, which typically evaluates to "false" in an if statement, it will always evaluate to true in this context.
So, instead of this:
-----
if( $_FILES [ 'userfile' ][ 'error' ]) <
// handle the error
> else <
// process
>
?>
-----
You have to do this:
-----
if( $_FILES [ 'userfile' ][ 'error' ]== 0 ) <
// process
> else <
// handle the error
>
?>
-----
Also, ctype_digit fails, but is_int works. If you're wondering. no, it doesn't make any sense.
You ask the question: Why make stuff complicated when you can make it easy? I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement. In a loop, that would be deadly. try this instead:
-----
$error_types = array(
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.' ,
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.' ,
'The uploaded file was only partially uploaded.' ,
'No file was uploaded.' ,
6 => 'Missing a temporary folder.' ,
'Failed to write file to disk.' ,
'A PHP extension stopped the file upload.'
);
// Outside a loop.
if( $_FILES [ 'userfile' ][ 'error' ]== 0 ) <
// process
> else <
$error_message = $error_types [ $_FILES [ 'userfile' ][ 'error' ]];
// do whatever with the error message
>
// In a loop.
for( $x = 0 , $y = count ( $_FILES [ 'userfile' ][ 'error' ]); $x < $y ;++ $x ) <
if( $_FILES [ 'userfile' ][ 'error' ][ $x ]== 0 ) <
// process
> else <
$error_message = $error_types [ $_FILES [ 'userfile' ][ 'error' ][ $x ]];
// Do whatever with the error message
>
>
// When you're done. if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory
unset( $error_types );
?>
When uploading a file, it is common to visit the php.ini and set up upload_tmp_dir = /temp but in the case of some web hostess as fatcow you need to direct not only /tmp but upload_tmp_dir = /hermes/walnaweb13a/b345/moo.youruser/tmp
I have expanded @adam at gotlinux dot us's example a bit with proper UPLOAD_FOO constants and gettext support. Also UPLOAD_ERR_EXTENSION is added (was missing in his version). Hope this helps someone.
class Some /**
* Upload error codes
* @var array
*/
private static $upload_errors = [];
public function __construct () // Init upload errors
self :: $upload_errors = [
UPLOAD_ERR_OK => _ ( 'There is no error, the file uploaded with success.' ),
UPLOAD_ERR_INI_SIZE => _ ( 'The uploaded file exceeds the upload_max_filesize directive in php.ini.' ),
UPLOAD_ERR_FORM_SIZE => _ ( 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.' ),
UPLOAD_ERR_PARTIAL => _ ( 'The uploaded file was only partially uploaded.' ),
UPLOAD_ERR_NO_FILE => _ ( 'No file was uploaded.' ),
UPLOAD_ERR_NO_TMP_DIR => _ ( 'Missing a temporary folder.' ),
UPLOAD_ERR_CANT_WRITE => _ ( 'Cannot write to target directory. Please fix CHMOD.' ),
UPLOAD_ERR_EXTENSION => _ ( 'A PHP extension stopped the file upload.' ),
];
>
>
?>
In regards to the dud filename being sent, a very simple way to check for this is to check the file size as well as the file name. For example, to check the file size simple use the size attribute in your file info array:
if( $_FILES [ "file_id" ][ "size" ] == 0 )
<
// . PROCESS ERROR
>
?>
I noticed that on PHP-4.3.2 that $_FILES can also not be set if the file uploaded exceeds the limits set by upload-max-filesize in the php.ini, rather than setting error $_FILES["file"]["error"]
UPLOAD_ERR_PARTIAL is given when the mime boundary is not found after the file data. A possibly cause for this is that the upload was cancelled by the user (pressed ESC, etc).
Note: something that might surprise you, PHP also provides a value in the $_FILES array, if the input element has no value at all, stating an error UPLOAD_ERR_NO_FILE.
So UPLOAD_ERR_NO_FILE is not an error, but a note that the input element just had no value. Thus you can't rely on the $_FILES array to see if a file was provided. Instead you have to walk the array and check every single damn entry - which can be quite difficult since the values may be nested if you use input elements named like "foo[bar][bla]".
Seems like PHP just introduced you to yet another common pitfall.
I've been playing around with the file size limits and with respect to the post_max_size setting, there appears to be a hard limit of 2047M. Any number that you specify above that results in a failed upload without any informative error describing what went wrong. This happens regardless of how small the file you're uploading may be. On error, my page attempts to output the name of the original file. But what I discovered is that this original file name, which I maintained in a local variable, actually gets corrupted. Even my attempt to output the error code in $_FILES['uploadedfiles']['error'] returns an empty string/value.
Hopefully, this tidbit will save someone else some grief.
This updates "adam at gotlinux dot us" above and makes it version aware, and also adds newer constants to the array.
The reason we want to check the version is that the constants are not defined in earlier versions, and they appear later in the array. They would effectively overwrite the "0" index (no error) with an error message when the file actually uploaded fine.
It also drops the constant's value (0,1,2, etc) for the errors, in the likely event that they are changed later (the code should still work fine).
$upload_errors = array(
0 => "There is no error, the file uploaded with success"
, UPLOAD_ERR_INI_SIZE => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, UPLOAD_ERR_FORM_SIZE => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded"
, UPLOAD_ERR_NO_FILE => "No file was uploaded"
);
if ( version_compare ( PHP_VERSION , '5.0.3' ) >= 0 )
$upload_errors [ UPLOAD_ERR_NO_TMP_DIR ] = "Missing a temporary folder" ;
if ( version_compare ( PHP_VERSION , '5.1.0' ) >= 0 )
$upload_errors [ UPLOAD_ERR_CANT_WRITE ] = "Failed to write to disk" ;
if ( version_compare ( PHP_VERSION , '5.2.0' ) >= 0 )
$upload_errors [ UPLOAD_ERR_EXTENSION ] = "File upload stopped by extension" ;
?>
[Well just a little note. ]
That UploadException class example posted on top by anonymous is great. It works good. But there is a certain problem. You know there are two sides to generating errors.
First -> for the client side.
Second -> for the developers who will use your script
But i see only one side to generating Exceptions. ie For the developers.
Why ? Because when you generate an Exception, your script will come to an halt and do whatever you have defined in catch clause.
Now you dont want any client to see the Exception, do you ? I will not. The client will want to know what error occured in simple words they can understand instead of wanting their web app crashed if upload fails. So, dont generate exceptions. These errors should be collected and shown to client in an elegant way. That's a little advice.
Keep developing smarter.
Just found out that it is very important to define the
input type="hidden" name="MAX_FILE_SIZE" value=.
AFTER defining the input type="FILE" name=.
in your html/php.
If you swap them around, you will keep getting the filesize exceeded (error 2)!
Hope this helps.
Roger
enctype="multipart/form-data" works fine
Upload doesnt work, and no error?
actually, both $_FILES and $_REQUEST in the posted to script are empty?
just see, if "post_max_size" is lower than the data you want to load.
in the apache error log, there will be an entry like "Invalid method in request". and in the access log, there will be two requests: one for the POST, and another that starts with all "----" and produces a 501.
For those reading this manual in german (and/or probably some other languages) and you miss error numbers listed here, have a look to the english version of this page ;)
1. And what about multiple file upload ? - If there is an UPLOAD_ERR_INI_SIZE error with multiple files - we can`t detect it normaly ? . because that we have an array, but this error returns null and can`t use foreach. So, by having a multiple upload, we can`t normaly inform user about that.. we can just detect, that sizeof($_FILES["file"]["error"]) == 0 , but we can`t actualy return an error code. The max_file_size also is not an exit, becouse it refers on each file seperatly, but upload_max_filesize directive in php.ini refers to all files together. So, for example, if upload_max_filesize=8Mb , max_file_size = 7Mb and one of my files is 6.5Mb and other is 5Mb, it exeeds the upload_max_filesize - cant return an error, becouse we don`t know where to get that error.
Unfortunately we cannot get the file sizes on client side, even AJAX normaly can`t do that.
2. If in file field we paste something, like, D:\whatever , then there also isn`t an error to return in spite of that no such file at all.
Файл конфигурации ( php.ini ) считывается при запуске PHP. Для версий серверных модулей PHP это происходит только один раз при запуске веб-сервера. Для CGI и CLI версий это происходит при каждом вызове.
- По месту расположения модуля SAPI ( PHPIniDir директива Apache 2, -c параметр командной строки CGI и CLI)
- Переменная среды PHPRC .
- Местоположение файла php.ini может быть указано для различных версий PHP. Корневой ключ реестра зависит от разрядности операционной системы и установки PHP. Для 32-разрядного PHP на 32-разрядной Windows или 64-разрядного PHP и 64-разрядной Windows используйте [(HKEY_LOCAL_MACHINE\SOFTWARE\PHP] . Для 32-разрядного PHP на 64-разрядной Windows [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PHP] . Следующие ключи реестра исследуются при поиске для установок с совпадающей разрядностью: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z] , [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] и [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x] , где x, y и z подразумевают major, minor и release версии PHP. Для 32-разрядного PHP на 64-разрядной Windows ключи реестра будут другими: [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x.y.z] , [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x.y] и [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x] . Если также имеется значение IniFilePath в любом из этих ключей, то местонахождение php.ini будет определено первым ключом по порядку (только для Windows).
- [HKEY_LOCAL_MACHINE\SOFTWARE\PHP] или [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PHP] , значение IniFilePath (только для Windows).
- Текущая директория (исключая CLI).
- Директория веб-сервера (для модулей SAPI) или директория PHP (иначе в Windows).
- В директории Windows ( C:\windows или C:\winnt ) (для Windows) или --with-config-file-path с выбором при компиляции.
Если файл php-SAPI.ini существует (где SAPI - это тип интерфейса, который используется, например, php-cli.ini или php-apache.ini ), то он используется вместо php.ini . Тип интерфейса между веб-сервером и PHP может быть определён с помощью функции php_sapi_name() .
Замечание:
Веб-сервер Apache изменяет текущую директорию на корневую при запуске, в результате чего PHP считывает php.ini из корневой файловой системы, если файл существует.
В php.ini можно использовать переменные окружения, как показано ниже.
Директивы php.ini , обрабатываемые модулями, описаны на соответствующих страницах модулей. Список директив ядра имеется в приложении. Не все директивы PHP документированы в этом руководстве: для ознакомления с полным списком директив доступных в вашей версии PHP, прочитайте комментарии вашего php.ini . Кроме того, вы можете найти полезной » последнюю версию php.ini из Git.
Возможно обращаться к существующим ini-переменным из ini-файлов. Пример: open_basedir = $ ":/new/dir" .
Другие решения
Если вы используете Windows 10 с оболочкой Bash, вы можете запустить
Это покажет все загруженные файлы конфигурации. Люди, которые чаще работают в Windows, могут определить родной способ выполнения эквивалентной операции.
При копировании или переименовании файла php.ini убедитесь, что он изменяет расширение файла с .ini-development (или .ini-production, в зависимости от того, какой файл вы используете) на просто .ini. Если вы не видите расширений в файлах, вы можете изменить их, нажав> просмотреть и выбрав расширения имени файла флажок в крайнем правом углу.
Кроме того, вы можете посмотреть на столбец типа файла, где он должен сказать конфигурационный файл если расширение файла изменилось на .ini.
Сканирование директорий
Существует возможность сконфигурировать PHP для сканирования директорий в поисках .ini-файлов после считывания php.ini . Это можно сделать на моменте компиляции, указав опцию --with-config-file-scan-dir. Сканирование директорий может быть переопределено во время исполнения установкой переменной среды PHP_INI_SCAN_DIR .
Можно сканировать несколько директорий, разделяя их разделителем, используемом в вашей операционной системе ( ; в Windows, NetWare и RISC OS; : на всех остальных платформах; в PHP есть константа PATH_SEPARATOR , которую можно использовать) Если PHP_INI_SCAN_DIR пуста, то PHP также будет сканировать директорию, заданную на этапе компиляции с помощью --with-config-file-scan-dir.
В каждой директории PHP сканирует все файлы заканчивающиеся на .ini в алфавитном порядке. Список всех загруженных файлов в том порядке, в котором они были загружены, доступен с помощью функции php_ini_scanned_files() , либо при запуске PHP с опцией --ini.
Я знаю, что по этому поводу уже есть много вопросов, но я просмотрел каждый из них и ничего не нашел.
Я пытаюсь установить платформу электронной коммерции Magento, но мне нужно установить несколько расширений PHP, прежде чем я смогу продолжить (а именно: curl, xsl, intl, mbstring, openssl и gd)
Я прочел и обнаружил, что для их включения мне нужно удалить точку с запятой перед ними в php.ini файл, поэтому я перешел к C:\php и искал, но найти можно только php.ini-development а также php.ini-production , который, глядя на другую ветку, тоже не то, что я хочу.
Я также читал, что иногда это просто файл с именем php, но я не могу найти его ни в C:\php папка
Затем я выполнил phpinfo(); команда в файле php и запустила его, получив такой результат:
Затем я посмотрел в C:\Windows папка безрезультатно, и я не знаю, как мне найти php.ini файл, чтобы я мог удалить точку с запятой и загрузить расширения PHP.
Любая помощь будет оценена.
Читайте также: