PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Erreurs classiques> <Gestion des chargements de fichiers
Last updated: Fri, 05 Sep 2008

view this page in

Explication sur les messages d'erreurs de chargement de fichiers

Depuis PHP 4.2.0, PHP retourne un code d'erreur approprié dans le tableau de fichiers. Ce code d'erreur est accessible à l'index ['error'] du tableau, qui est créé durant le téléchargement, par PHP. En d'autres termes, le message d'erreur est accessible dans la variable $_FILES['userfile']['error'].

UPLOAD_ERR_OK

Valeur : 0. Aucune erreur, le téléchargement est correct.

UPLOAD_ERR_INI_SIZE

Valeur : 1. Le fichier téléchargé excède la taille de upload_max_filesize, configurée dans le php.ini.

UPLOAD_ERR_FORM_SIZE

Valeur : 2. Le fichier téléchargé excède la taille de MAX_FILE_SIZE, qui a été spécifiée dans le formulaire HTML.

UPLOAD_ERR_PARTIAL

Valeur : 3. Le fichier n'a été que partiellement téléchargé.

UPLOAD_ERR_NO_FILE

Valeur : 4. Aucun fichier n'a été téléchargé.

UPLOAD_ERR_NO_TMP_DIR

Valeur : 6. Un dossier temporaire est manquant. Introduit en PHP 4.3.10 et PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE

Valeur : 7. Échec de l'écriture du fichier sur le disque. Introduit en PHP 5.1.0.

UPLOAD_ERR_EXTENSION

Valeur : 8. L'envoi de fichier est arrêté par l'extension. Introduit en PHP 5.2.0.

Note: Ces constantes sont apparues en PHP 4.3.0.



Erreurs classiques> <Gestion des chargements de fichiers
Last updated: Fri, 05 Sep 2008
 
add a note add a note User Contributed Notes
Explication sur les messages d'erreurs de chargement de fichiers
RusselMD
10-Apr-2008 05:21
# stephen at poppymedia dot co dot uk

Hi!

In this case, you can use $_SERVER['CONTENT_LENGTH'] after trying to upload file. This variable returns size  of uploaded file, even if upload failed.
albert at 374c dot nl
23-Jan-2008 09:32
@Anonymous [below me]

If a new error constant would be introduced, your script would ignore it and assume that the upload went OK.

I've included a better version below:

<?php
$uploadErrors
= array(
   
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 => 'Failed to write file to disk.',
   
UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
);

$errorCode = $_FILES['myUpload']['error'];

// if($errorCode !== UPLOAD_ERR_OK && isset($uploadErrors[$errorCode]))
if($errorCode !== UPLOAD_ERR_OK)
{
    if(isset(
$uploadErrors[$errorCode]))
       
throw new Exception($uploadErrors[$errorCode]);
    else
       
throw new Exception("Unknown error uploading file.");
}
?>
Anonymous
30-Dec-2007 11:54
<?php
$uploadErrors
= array(
   
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 => 'Failed to write file to disk.',
   
UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
);

$errorCode = $_FILES['myUpload']['error'];

if(
$errorCode !== UPLOAD_ERR_OK && isset($uploadErrors[$errorCode]))
{
   
throw new Exception($uploadErrors[$errorCode]);
}
?>
info at foto50 dot com
03-Jul-2007 11:03
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 ;)
littleDave
22-Jun-2007 03:44
@ belowtherim2000 at yahoo dot com:

This hard limit 2047M has to do with 32bit integer values. It seems php handles the post_max_size as a signed integer which has the borders -2147483648 and +2147483648. Unsigned integer has 0 and 4294967296. If you enter a value greater than 2147483648, there happens a rap-arround internally (which means the number is NOT 2147483649, it is
-2147483648). So you can not upload files which are greater than -2147483648 bytes. It might work if you would enter "4096M", than you would be able to upload data up to 2 megabytes
belowtherim2000 at yahoo dot com
21-Jun-2007 03:25
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.
drm at (melp) dot nl
08-May-2007 02:21
In reply to "svenr at selfhtml dot org"

Since uploaded files are sent in the HTTP request body following the MAX_UPLOAD_FILE_SIZE file (that's why you need to put it before the file field in HTML), PHP can stop receiving the rest of the HTTP request body when the Content-Length header of that particular part of the request is more than the value of the MAX_FILE_SIZE field.

Therefore, using the field renders a convenience, not a security fix, since the server can stop receiving the request body and start responding right after PHP has decided that the content-length is more (bytes) than allowed. This means that the client doesn't have to upload the entire body of the http-request, just to see an error appear.

You can test this by using the field on a local server and for instance upload a 700MB iso or avi file or so. You will see that the server is quite quick in responding to say that the file is too large, even though the file hasn't been uploaded completely.

Conclusively, MAX_FILE_SIZE isn't that useless after all (as upload_max_filesize is a PHP_INI_PERDIR setting) but you should be cautious to only use it as a convenience thing for the client, not as a security thing.
svenr at selfhtml dot org
24-Apr-2007 12:15
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.

The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).
abuse dot bernhardkroll at arcor dot de
06-Apr-2007 03:08
For a multifile upload try this:

<?php

foreach($_FILES as $file)
{
    if(
$file['error'] == 0 && $file['size'] > 0)
    {
       
move_uploaded_file($file['tmp_name'], $targetdir.$file['name']);
    }
}

?>
web att lapas dott id dott lv
23-Feb-2007 02:49
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.
rjg4013 at rit dot edu
06-Jul-2006 11:53
In response to Hans:  The problem with your switch statement is that it never allows for no errors, i.e. the UPLOAD_ERR_OK val.  So to still allow room for further errors, yet notice a no-error case, this needs to be addressed:

<?php
switch ($filearray["error"]) {
   case
UPLOAD_ERR_OK:
       break;
   case
UPLOAD_ERR_INI_SIZE:
      
throw new Exception("The uploaded file exceeds the upload_max_filesize directive (".ini_get("upload_max_filesize").") in php.ini.");
       break;
   case
UPLOAD_ERR_FORM_SIZE:
      
throw new Exception("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.");
       break;
   case
UPLOAD_ERR_PARTIAL:
      
throw new Exception("The uploaded file was only partially uploaded.");
       break;
   case
UPLOAD_ERR_NO_FILE:
      
throw new Exception("No file was uploaded.");
       break;
   case
UPLOAD_ERR_NO_TMP_DIR:
      
throw new Exception("Missing a temporary folder.");
       break;
   case
UPLOAD_ERR_CANT_WRITE:
      
throw new Exception("Failed to write file to disk");
       break;
   default:
      
throw new Exception("Unknown File Error");
}
?>
-
20-Jan-2006 12:26
Thank you stephen, that was very helpful ;-)

So, to repeat it for all, check your php.ini,

post_max_size

should be bigger than

upload_max_filesize

, otherwise you will not be able to report the correct error in case of a too big upload ! Also check the max-execution-time (upload-time could be added to execution-time).
stephen at poppymedia dot co dot uk
27-Sep-2005 12:05
if post is greater thanpost_max_size set in php.ini

$_FILES and $_POST will return empty
hans at lintoo dot dk
15-Jul-2005 10:18
or perhaps this:
<?php
switch ($filearray["error"]) {
    case
UPLOAD_ERR_INI_SIZE:
       
throw new Exception("The uploaded file exceeds the upload_max_filesize directive (".ini_get("upload_max_filesize").") in php.ini.");
    break;
    case
UPLOAD_ERR_FORM_SIZE:
       
throw new Exception("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.");
    break;
    case
UPLOAD_ERR_PARTIAL:
       
throw new Exception("The uploaded file was only partially uploaded.");
    break;
    case
UPLOAD_ERR_NO_FILE:
       
throw new Exception("No file was uploaded.");
    break;
    case
UPLOAD_ERR_NO_TMP_DIR:
       
throw new Exception("Missing a temporary folder.");
    default:
       
throw new Exception("An unknown file upload error occured");
}
?>
adam at gotlinux dot us
27-May-2005 04:28
This is probably useful to someone.
<?
array(
        0=>"There is no error, the file uploaded with success",
        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
        3=>"The uploaded file was only partially uploaded",
        4=>"No file was uploaded",
        6=>"Missing a temporary folder"
);
?>
sysadmin at cs dot fit dot edu
16-Feb-2005 04:13
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"]
krissv at ifi.uio.no
28-Jan-2005 01:11
When $_FILES etc is empty like Dub spencer says in the note at the top and the error is not set, that might be because the form enctype isnt sat correctly. then nothing more than maybe a http server error happens.

enctype="multipart/form-data" works fine
Dub Spencer
26-Nov-2004 03:56
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.
tyler at fishmas dot org
04-Nov-2004 04:08
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
}

Erreurs classiques> <Gestion des chargements de fichiers
Last updated: Fri, 05 Sep 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites