Наиболее распространенные ошибки

Опция 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 достаточно велико.

Начиная с версии PHP 5.2.12, опция max_file_uploads контролирует максимальное количество загружаемых файлов в течение одного запроса. Если загружается большее количество файлов, чем указано в этом ограничении, то массив $_FILES прекратит дальнейшую обработку файлов по достижении этого ограничения. Например, если max_file_uploads установлено в 10, то $_FILES никогда не будет содержать больше 10 элементов.

Если не проверять, с какими файлами вы работаете, пользователи могут получить доступ к конфиденциальной информации, расположенной в других директориях.

Следут заметить, что CERN httpd может отсечь все, что идет после первого пробела в получаемом от клиента заголовке content-type. Если у вас именно такой случай, CERN httpd не сможет корректно загрузить файлы.

Поскольку разные системы по-разному работают с файловой структурой, нет никаких гарантий того, что файлы с экзотическими именами (например, которые содержат пробельные символы) будут обработаны корректно.

Разработчики не должны использовать одинаковые имена для обычных полей ввода (тег input) и полей выбора файла в пределах одной и той же формы (например, используя имя для тега input наподобие foo[]).

Коментарии

The macintosh OS (not sure about OSx) uses a dual forked file system, unlike the rest of the world ;-). Every macintosh file has a data fork and a resource fork. When a dual forked file hits a single forked file system, something has to go, and it is the resource fork. This was recognized as a problem (bad idea to begin with) and apple started recomending that developers avoid sticking vital file info in the resource fork portion of a file, but some files are still very sensitive to this. The main ones to watch out for are macintosh font files and executables, once the resource fork is gone from a mac font or an executable it is useless. To protect the files they should be stuffed or zipped prior to upload to protect the resource fork. 

Most mac ftp clients (like fetch) allow files to be uploaded in Macbinhex, which will also protect the resource fork when transfering files via ftp. I have not seen this equivilent in any mac browser (but I haven't done too much digging either).

FYI, apple does have an old utility called ResEdit that lets you manipulate the resource fork portion of a file.
2003-02-04 10:16:25
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
It's important that the variable 'open_basedir' in php.ini isn't  set to a directory that doesn't not includes tempupload directory
2003-04-28 06:59:11
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
For apache, also check the LimitRequestBody directive.
If you're running a Red Hat install, this might be set in /etc/httpd/conf.d/php.conf.
By default, mine was set to 512 KB.
2003-06-09 09:59:06
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
Here is another that may make your upload fall over.  If you are using Squid or similar proxy server make sure that this is not limiting the size of the HTTP headers. This took me weeks to figure out!
2003-10-21 12:53:23
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
Note that, when you want to upload VERY large files (or you want to set the limiters VERY high for test purposes), all of the upload file size limiters are stored in signed 32-bit ints.  This means that setting a limit higher than about 2.1 GB will result in PHP seeing a large negative number.  I have not found any way around this.
2004-08-11 05:35:24
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
Took me a while to figure this one out...

I think this is actually a header problem, but it only
happens when doing a file upload.

If you attept a header("location:http://...) redirect after
processing a $_POST[''] from a form doing a file upload
(i.e. having enctype="multipart/form-data"), the redirect
doesn't work in IE if you don't have a space between
location: & http, i.e.
header("location:http://...)  vs
header("location: http://...)

===================================
<?php
if ($_POST['submit']=='Upload') {
   
// Process File and the redirect...
   
header("location: http://"..."/somewhere.php");
    exit;
}
?>
<html><head></head><body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="20000">
    Your file: <input name="filename" type="file">
    <input name="submit" type="submit" value="Upload">
</form>
</body></html>
===================================

This only happens if all of the following are true:
header("location:http://...) with no space
Form being processed has enctype="multipart/form-data"
Browser=IE

To fix the problem, simply add the space.

Hope this helps someone else.
2005-05-22 04:27:40
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
If you want to use open_basedir for securing your server (which is highly recommended!!!) remember to add your tmp dir to the open_basedir value in php.ini.

Example: open_basedir = <your htdocs root, etc...>:/tmp

(Tested on gentoo Linux, Apache 2.2, PHP 5.1.6)
2006-12-09 12:02:44
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
Автор:
A responce to admin at creationfarm dot com, Mac OS X and Windows running on a NTFS disk also uses a multi stream file system. Still only the data stream in transfared on http upload. It is preferable to pack Mac OS X files in .dmg files rathere then zip but the avarage user will find zip much easir and they are supported on more platforms.
2007-10-02 06:22:06
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
In case of non-deterministic occurence of the UPLOAD_ERR_PARTIAL error:  The HTTPD (e.g. Apache) should respond with a 'Accept-Ranges: none' header field.
2009-12-07 01:57:48
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
Автор:
If using IIS 7.0 or above, the Request Filtering is enabled by default and the max allowed content length is set to 30 MB.

One must change this value if they want to allow file uploads of more than 30 MB.

Sample web.config entry:

<configuration>
    </system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="314572800"/>
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

The above setting will allow 300 MB of data to be sent as a request. Hope this helps someone.
2009-12-11 22:23:23
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
[Editor's note: to be more precise, MAX_FILE_SIZE can't exceed PHP_INT_MAX before PHP 7.1.]

Please note that the field MAX_FILE_SIZE cannot exceed 2147483647. Any greater value will lead to an upload error that will be displayed at the end of the upload

This is explained by the related C code :
if (!strcasecmp(param, "MAX_FILE_SIZE")) {
    max_file_size = atol(value);
}

The string is converted into a long int, which max value is... 2147483647

Seems to be corrected since php-7.1.0beta3 (https://github.com/php/php-src/commit/cb4c195f0b85ca5d91fee1ebe90105b8bb68356c)
2016-09-09 10:48:26
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html
Автор:
Please be advised that setting a large post_max_size or upload_max_filesize for a complete server or a complete virtual host is not a good idea as it may lead to increased security risks.

The risk is that an attacker may send very large POST requests and overloading your server memory and CPU as it has to parse and process those requests before handling them to your PHP script.

So it's best to limit changing this setting to some files or directories. For example if I want to /admin/files/ and /admin/images/ I can use:

<If "%{REQUEST_URI} =~ m!^/admin/(files|images)/! && -n %{HTTP_COOKIE}">
    php_value post_max_size 256M
    php_value upload_max_filesize 256M
</If>

I also require the request to have a cookie to avoid basic attacks. This will not protect you against attacks coming from non-authenticated users, but may delay any attack.

This setting can be used in Apache server configuration files, and .htaccess files as well.
2022-09-15 00:06:17
http://php5.kiev.ua/manual/ru/features.file-upload.common-pitfalls.html

    Поддержать сайт на родительском проекте КГБ