PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previousCookiesErreurs classiquesnext
Last updated: Tue, 11 Jun 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Czech | Dutch | Finnish | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

Chapitre 19. Gestion des chargements de fichier

Chargements de fichiers par m�thode POST

PHP est capable de recevoir des fichiers �mis par un navigateur conforme � la norme RFC-1867 (c'est-�-dire Netscape Navigator 3 ou sup�rieur, Microsoft Internet Explorer 3 avec un patch de Microsoft, ou sup�rieur sans le patch). Cette fonctionnalit� permet de charger des fichiers textes ou binaires. Avec l'authentification et les fonctions de manipulation des fichiers, vous avez un contr�le total sur le chargement et la gestion des fichiers charg�s.

Notez bien que PHP supporte aussi le chargement par la m�thode PUT comme dans le navigateur Netscape Composer et les clients Amaya du W3C. Reportez-vous au chapitre sur le support de la m�thode PUT.

Un �cran de chargement de fichiers peut �tre constitu� en cr�ant un formulaire de la mani�re suivante :

Exemple 19-1. Formulaire de chargement de fichier

<FORM ENCTYPE="multipart/form-data" ACTION="_URL_" METHOD="POST">
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000">
Envoyez ce fichier : <INPUT NAME="userfile" TYPE="file">
<INPUT TYPE="submit" VALUE="Send File">
</FORM>
Le param�tre _URL_ doit pointer sur un fichier PHP. L'option MAX_FILE_SIZE cach�e doit pr�c�der le nom du fichier � charger, et repr�sente la taille maximale du fichier � charger. La valeur est donn�e en octets. Dans ce script, les valeurs suivantes doivent �tre d�finies pour assurer un chargement correct :

En PHP 3, les variables suivantes seront d�finies dans le script de destination, en cas de t�l�chargement r�ussi, et en supposant que register_globals est activ� dans le fichier php.ini. Si track_vars est activ�, elles seront aussi disponibles dans le dossier $HTTP_POST_VARS. Notez que les noms des variables suivantes supposent que nom du fichier t�l�charg� est 'userfile', comme pr�sent� dans l'exemple ci-dessus.

  • $userfile - Le nom temporaire du fichier qui sera charg� sur la machine serveur.

  • $userfile_name - Le nom du fichier original sur le syst�me de l'envoyeur.

  • $userfile_size - La taille du fichier envoy� en octets.

  • $userfile_type - Le type MIME du fichier, si le navigateur a fourni cette information. Par exemple, "image/gif".

Notez que "$userfile" prend la valeur qui est pass�e dans le champs INPUT de type TYPE=file. Dans l'exemple ci-dessus, nous avons choisi de l'appeler "userfile".

En PHP 4, le comportement est l�g�rement diff�rent, car c'est la variable d'environnement $HTTP_POST_FILES, qui contiendra les informations sur les fichiers t�l�charg�s. Ces informations sont disponibles dans si l'option track_vars est activ�e, mais track_vars est toujours activ�e dans les versions de PHP sup�rieures � la version 4.0.2.

Le contenu du tableau $HTTP_POST_FILES d�crit ci-dessous. Notez que l'on suppose ici que le nom du fichier t�l�charg� est 'userfile', comme pr�sent� dans l'exemple ci-dessus :

$HTTP_POST_FILES['userfile']['name']

Le nom du fichier original sur la machine source.

$HTTP_POST_FILES['userfile']['type']

Le type MIME du fichier, si le navigateur a fourni cette information. Par exemple, "image/gif".

$HTTP_POST_FILES['userfile']['size']

La taille du fichier envoy�, en octets.

$HTTP_POST_FILES['userfile']['tmp_name']

Le nom temporaire du fichier qui sera charg� sur la machine serveur.

Les fichiers seront enregistr�s par d�faut dans le dossier des fichiers temporaires, � moins qu'un autre dossier n'ait �t� fourni avec la directive de configuration upload_tmp_dir du fichier php.ini. Le dossier par d�faut du serveur peut �tre modifi� gr�ce � la variable d'environnement TMPDIR, de l'utilisateur qui ex�cute PHP. Sa modification avec putenv() depuis un script PHP ne fonctionnera pas. Cette variable d'environnement peut aussi �tre utilis�e pour s'assurer que d'autres op�rations fonctionnent avec les fichiers t�l�charg�s.

Exemple 19-2. Validation de fichiers t�l�charg�s

Les exemples suivants fonctionnent sur les versions de PHP 3 sup�rieures � la version 3.0.16, et sup�rieures � la version 4.0.2 pour PHP 4. Reportez-vous � la section des fonctions pour �tudier is_uploaded_file() et move_uploaded_file().

<?;php
if (is_uploaded_file($userfile)) {
    copy($userfile, "/dossier/des/fichiers/telecharges/");
} else {
    echo "Attaque potentielle par fichier t�l�charg� : fichier '$userfile'.";
}
/* ...ou... */
move_uploaded_file($userfile, "/dossier/des/fichiers/telecharges");
?>

Pour les versions plus anciennes de PHP, vous devrez faire quelque chose comme ceci :

<?;php
/* Test du fichier t�l�charg�. */
function is_uploaded_file($filename) {
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* L'utilisateur peut avoir un slash final dans php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}
if (is_uploaded_file($userfile)) {
    copy($userfile, "/place/to/put/uploaded/file");
} else {
    echo "Attaque potentielle par fichier t�l�charg� : fichier '$userfile'.";
}
?>

Note�: Cela ne fonctionnera PAS avec les versions de PHP 4 sup�rieure � 4.0.2. Cela repose sur des fonctionnalit�s internes � PHP qui ont �volu� apr�s cette version.

Le script PHP qui re�oit le fichier charg� doit pouvoir g�rer le fichier de mani�re appropri�e. Vous pouvez utiliser la variable $file_size pour recaler tous les fichiers qui sont trop gros ou trop petits. Vous pouvez utiliser la variable $file_type pour recaler les fichiers qui n'ont pas le bon type. Quelques soient les actions, ce script doit pouvoir supprimer le fichier du dossier temporaire, ou le d�placer ailleurs.

Le fichier sera automatiquement effac� du fichier temporaire � la fin du script, s'il n'a pas �t� d�plac� ou renomm�.

User Contributed Notes
Gestion des chargements de fichier
add a note about notes

05-Jan-2001 02:36

$HTTP_RAW_POST_DATA --

You'll usually access variables from forms sent via POST method by just
accessing the associated PHP global variable.

However, if your POST data is not URI encoded (i.e., custom application
that's not form-based) PHP won't parse the data into nice variables for
you.  You will need to use $HTTP_RAW_POST_DATA to access the raw data
directly. (This should return a copy of the data given to the PHP process
on STDIN; note that you wan't be able to open STDIN and read it yourself
because PHP already did so itself.)


26-Aug-2001 06:20

File uploading with 'safe mode' turned on is a real problem.  (As is 'safe
mode' in its present incarnation, generally.)  The temporary file is
rarely owned by the same userid who created the page.  But PHP, having
just created this file, ought to know that and ought to handle it more
sensibly.

It seems to me that 'safe mode' could be more well-defined, e.g. with a
set of user-IDs that are allowed to create pages, any one of whose IDs
should be accepted.

Certainly 'safe mode' should be aware of uploads.  In its present form,
uploading essentially rules-out the use of safe mode completely.  :-/

16-Jan-2002 07:09
This example is was a bit confusing for me... didn't get a file to upload
till I looked here.


30-Jan-2002 01:33

Some restrictive firewalls may not let file uploads happen via a form with
enctype="multipart/form-data".

We were having problems with an upload script hanging (not returning
content) when a file was uploaded through a remote office firewall.
Removing the enctype parameter of the form allowed the form submit to
happen but then broke the file upload capability. Everything but the file
came through. Using a dial-in or other Internet connection (bypassing the
bad firewall) allowed everything to function correctly.

So if your upload script does not respond when uploading a file, it may be
a firewall issue.


02-Feb-2002 12:02

There is one thing open.

I am using PHP 4.1.1 on Apache / Linux. The upload procedure _requires_
that you have a line that sets the maximum file size in your form:

<input type="hidden" name="MAX_FILE_SIZE"
value="100000">

(value in bytes)


06-Feb-2002 12:04

There seems to be something weird going on when uploading a picture and
it's headers. If a file is created on the server through move or copy -
the file can apparently only be seen and used through the img tag in html.

So in other terms - you create a database entry (id, name, whatever) for
the upload, and construct the name of the uploaded picture that way. Refer
or call it by the IMG tag - it will show correctly.

When trying to open the file independently in a browser or GIMP or
Photoshop - there seems to be something wrong with the header of the file,
and the application will not show the picture. 

Maybe this is a bug, dunno - but it is something strange that kept me
searching for some time :(


12-Feb-2002 10:55

Well so far none of the suggestions mentioned here has worked for me. I am
currently using the following pieced together from all the different
comments and continue to get an "attack" error. The file I am
unloading is 4Bytes and I have the MAX-SIZE set to 100000. Here is the
code:

<?
print "$userfile = userfile
"; print "$userfile_name = userfile_name
"; print "$userfile_type = userfile_type
"; print "$userfile_size = userfile_size
"; print "$tmp_name = tmp_name
"; // In PHP 4.1.0 or later, $_FILES should be used instead of $HTTP_POST_FILES. if (is_uploaded_file($HTTP_POST_FILES['userfile']['tmp_name'])) { copy($HTTP_POST_FILES['userfile']['tmp_name'], "f:\\place\\to\\file\\"); } else { echo "Possible file upload attack: filename '".$HTTP_POST_FILES['userfile']['name']."."; } /* ...or... */ move_uploaded_file($HTTP_POST_FILES['userfile']['tmp_name'], "f:\\place\\to\\file\\"); ?> Here is the result: = userfile test.txt = userfile_name text/plain = userfile_type = userfile_size = tmp_name Possible file upload attack: filename 'test.txt.


13-Feb-2002 09:28

<?php

//	Complete working file upload example, Win2KPro, Apache 1.3x, PHP 4.x

// 	Set this line in php.ini
// 	upload_tmp_dir = c:\inetpub\wwwroot\uploads

function handleupload() {
	if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
		$filename = $_FILES['userfile']['tmp_name'];
		print "$filename was uploaded successfuly
"; $realname = $_FILES['userfile']['name']; print "realname is $realname
"; print "copying file to uploads dir"; copy($_FILES['userfile']['tmp_name'], "c:\\inetpub\\wwwroot\\uploads\\".$realname); } else { echo "Possible file upload attack: filename ".$_FILES['userfile']['name']."."; } } ?> <html><body> <?php if ($act == "upload") { handleupload(); } ?> <form ENCTYPE="multipart/form-data" method="POST" action="ultest.php?act=upload"> File:<INPUT TYPE="FILE" NAME="userfile" SIZE="35">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000"> <input type="submit" value="Upload" name="B1">

Please click only <b>once</b> and wait for confirmation </form>

<a href=ultest.php>clear form</a> </body></html>


13-Feb-2002 05:11

i had many problems trying to do a multiple upload and insert into mysql, i
eventually cracked it

$ary=array($pic_name[$key],$name[$key]);
while(list($key) = each($ary)) {
    $query="insert into images (pics,name) values
('$pics_name[$key]', '$name[$key]')";
	$result = $db->query($query);
	print "".$query."
"; unset($pics_name[$key],$name[$key]); } using pic[] and name[] in the form


13-Feb-2002 10:58

I forgot to mention in my above example that this code goes into a file
named "ultest.php" that has the form and the upload handling all
in the same file.


15-Feb-2002 02:52

There's a strange issue with file uploading and mime types, it seems it
depends of the browser.. 

With a file upload system, the above code will show differents results :

echo "type :
".$HTTP_POST_FILES["image"]["type"]." name :
".$HTTP_POST_FILES["image_thb"]["name"]."
tmpname :
".$HTTP_POST_FILES["image"]["tmp_name"]."
size : ".$HTTP_POST_FILES["image"]["size"] ;

where 'image' is an input (type='file') field.

On IE, it gives :
type : image/pjpeg name : apercuclip.jpg tmpname : /tmp/phpwYQzWO size :
5182

Ok, normal, let's try another

On Netscape6 it gives :
type : image/jpeg name : apercuclip.jpg tmpname : /tmp/php6jgmQR size :
5182

note that the mime type is now image/jpeg and not image/pjpeg

On Opera6 : 
type : image/jpeg; name=\"apercuclip.jpg\" name : apercuclip.jpg
tmpname : /tmp/php655KLf size : 5182

Still image/jpeg, but there's also a "name" value ! weird
result..

So be careful with that while uploading file..


16-Feb-2002 01:01

Using PHP 4.0.6 (of my hosting provider).
I had to change that "handleupload"-function like this to get it
to work:

function handleupload() {
	global $HTTP_POST_FILES;

	if (is_uploaded_file($HTTP_POST_FILES['userfile']['tmp_name']))
	{
		$filename = $HTTP_POST_FILES['userfile']['tmp_name'];
		print "$filename was uploaded successfuly";
		$realname = $HTTP_POST_FILES['userfile']['name'];
		print "realname is $realname";
		print "copying file to uploads dir";
		copy($HTTP_POST_FILES['userfile']['tmp_name'],
"/place/to/put/".$realname);
	}
	else
	{
		echo "Possible file upload attack: filename" .
$_FILES['userfile']['name'] . ".
"; } } That array "$HTTP_POST_FILES" did not seem to be in scope? The variable "$_FILES" did not contain any value (empty) - using "$HTTP_POST_FILES" instead.


18-Feb-2002 05:55

The

enctype="multipart/form-data" 

part in the <form ...> field is very important, if you forget it you
won't get the $userfile, $userfile_name, $userfile_size, $userfile_type
veriables set (correctly). So if you're adding a File Input Field in a
form, don't forget to add the above part (I did it and wondered why the
vars were not set correctly).


27-Feb-2002 02:13

Some browsers label the type differently.  I found this out while trying to
restrict the file types that could be uploaded.  I created a simple script
that will let the user upload a file, and then print_r() the $_FILES
variables.  In Microsoft Internet Explorer 6.0.26 on Windows XP, I got
this result:

Array
(
    [file] => Array
        (
            [name] => command.com
            [type] => application/octet-stream
            [tmp_name] => C:\WINDOWS\TEMP\phpBE.tmp
            [size] => 50620
        )

)

Uploading the same file with the same script in Opera 6.01 (again on
Windows XP), I got this result:

Array
(
    [file] => Array
        (
            [name] => command.com
            [type] => application/octet-stream;
name="command.com"
            [tmp_name] => C:\WINDOWS\TEMP\phpBF.tmp
            [size] => 50620
        )

)

The tmp_name is obviously supposed to be different, but notice how the
name of the file was appened to type.  My solution is either (a) split()
at the semicolon and use the first element of that array, or (b), search
the type for the allowed filetypes (via strstr()).


27-Feb-2002 02:24

When uploading large files, I've found that the memory limit has to be
twice as large as the upload limit or else the PHP script will not be able
to move/copy the file to a new destination.


28-Feb-2002 06:28

Sorry, ofcourse i mean method and not action.


01-Mar-2002 10:12

Hi,
i am refering to the posting from 5th of February 2002 from
[email protected].

The problem ist not the header of the file but the rights. You have to
change it with chmod-function.


04-Mar-2002 08:05

When uploading very large files (greater than the default 8M) I found that
I had alter not only the "max_file_size" input and the php.ini
max_file_size limit, but ALSO the "post_max_size" variable in
the php.ini file.

Because I was submitting the file via a POST request, it would hit this
limit and deny the upload.


10-Mar-2002 09:15

Just wanted to tell users who wants to upload big files. For example 100 mb
or more.
Due to Bug #13094 you need the same amount of ram since the whole POST
will be saved in memory before handled. This is to be solved in 4.2.x


12-Mar-2002 06:02

move_uploaded_file(...) doesn't seem to work anymore for me. 
$_FILES['photo']['tmp_name'] has "/tmp/phpsomefile".. /tmp/ has
drwxrwxrwx permissions.. same with the destination directory.  I don't get
any errors, but the file disappears.


12-Mar-2002 05:50

I don't know if anybody else besides me will find this useful, but I just
wrote this bit to handle files that were uploaded to my server, but to not
allow them to overwrite an existing file with the same name.  This will
append the number 1 to the end of the file name and if THAT file exists,
it will increment the number until it finds an unused one.

One thing this wouldn't handle, is if you have periods in your directory
name for some reason.  Replace "images/profile" with your
directory path.

$glued_filename = "images/profile/" .
$_FILES['userfile']['name'];
   $i = 1;
     while (file_exists($glued_filename)) {
       $separated_filename = explode(".",$glued_filename);
       if (substr($separated_filename[0],-1) == $i) {
          $separated_filename[0] = substr($separated_filename[0], 0,
(strlen($separated_filename[0])-1));
          $i++;
       }

       $separated_filename[0] = $separated_filename[0] . "$i";
       $glued_filename = implode(".",$separated_filename);
     }

  copy($_FILES['userfile']['tmp_name'], $glued_filename);


15-Mar-2002 04:20

Your binary files may be uploaded incorrectly if you use modules what
recode characters. For example, for Russian Apache, you should use 
<Files ScriptThatReceivesUploads.php>
CharsetDisable On
</Files>


24-Mar-2002 06:38

As [email protected] mentioned above, including
enctype="multipart/form-data" as an attribute in your
<form> tag is very important for file uploads. If it's missing the
symptom will be that the file_name, file_size and file_type variables will
not be populated. If you're getting empty vars for these, check that you
have the enctype set.


24-Mar-2002 08:14

If no file was uploaded, you would probably expect the $userfile variable
(or whatever its name is) to be empty. But it isn't. It contains the
string "none" instead.

I don't know if this is true for all systems and configurations, but the
fact that it *might* be the case is reason enough *not* to use things like
that in order to check whether a file was uploaded:

// This is bad:
if($userfile == "")
  echo "You did not upload any file!";

Instead, you might want to check $userfile_size. But note that this method
makes no difference between NO and an EMPTY file:

// This is better:
if(!$userfile_size)
  echo "Either you did not upload any file, or you uploaded an empty
file!";


26-Mar-2002 02:31

using php 4.1.2 executable on windows 2000
$_FILES doesn't work for ['userfile']['tmp_name'],
It is always set to "none" ... use $HTTP_POST_FILES instead.


26-Mar-2002 08:57

I found [email protected]'s post on not overwriting an existing file by
appending a number to it very helpful.  The code unfortunately will not
work correctly once you get to filename10.foo.  Here is my rewrite of the
code to fix this, as well as allowing "." in the directory path
structure.  Maybe someone will find a bug in mine and/or make it more
efficient? 

define("c_FileUploadPath", "images/profile");
...
$FileName = $_FILES['userfile']['name'];
while (file_exists(c_FileUploadPath.$FileName)) {
  $SeperatedFileName = explode(".",$FileName);
  $FileNameNumIndex = 0;
  $FileNameNum = 0;
  while (is_numeric(substr($SeperatedFileName[0],-($FileNameNumIndex+1))))
    $FileNameNumIndex++;
  if ($FileNameNumIndex != 0) {
    $FileNameNum = substr($SeperatedFileName[0],-$FileNameNumIndex);
    $SeperatedFileName[0] = substr($SeperatedFileName[0], 0,           
(strlen($SeperatedFileName[0])-(strlen(strval($FileNameNum)))));
  }
  $NextFileNameNum = $FileNameNum + 1;
  $SeperatedFileName[0] = $SeperatedFileName[0] .
"$NextFileNameNum";
  $FileName = implode(".",$SeperatedFileName);
}
copy($_FILES['userfile']['tmp_name'], c_FileUploadPath . $FileName);


16-Apr-2002 10:50

Don't forget to allow file uploads by other users for the directory you use
as file-upload destination. Same thing for the temporary-file directory.

Just CHMOD the directories to 777 and it should work, granted the PHP code
itself is working okay.


20-Apr-2002 01:46

When i try using the copy function it says that open_dir restriction is
active.

What does this mean, also im using a virtual host.

Please help


24-Apr-2002 11:27

in reply to:
[email protected]
19-Apr-2002 07:46

open_dir restriction is when the folders on your server are read only for
the current user (public).

  You must edit the properties of that folder in some FTP program. 
Setting the properties to 777 should remove this problem.
Also typing
error_reporting(7);
in your code will hide the error from the users.


25-Apr-2002 12:01

Just another way to handle multiple uploads:

<?
function upload($FVARS) {
   for($i=0;$i<count($FVARS[file][tmp_name]);$i++) {
      $size=$FVARS[file][size][$i];     // filesize
      $type=$FVARS[file][type][$i];     // mime type 
      $name=$FVARS[file][name][$i];     // original name
      $temp=$FVARS[file][tmp_name][$i]; // temporary name
      if($size) { 
         //whatever to do with uploaded files
         echo "original name: $name<br />";
         echo "temporary name: $temp<br />";
         echo "mime type: $type<br />";
         echo "size: $size<hr />";
      }
   }
}

upload($HTTP_POST_FILES); // or $_FILES or whatever
?>

Using this function every <input type="file"
name="file[]"> will be handled.


01-May-2002 09:24

It seems that with PHP version 4.2.0, $userfile no longer contains the
string 'none' if the user has not selected a file.  $userfile instead will
be an empty string.


02-May-2002 10:53

To check to see if a file was actually uploaded, it is safer to check the
value of ($_FILES["name"]["size"] > 0) than to
check (!empty($_FILES["name"]["tmp_name"])) beacuse
some versions of PHP will store 'none' in
$_FILES["name"]["tmp_name"] while others will leave it
empty in the case od a missing file.


04-May-2002 12:11

Just another way I found to keep an uploaded file from overwriting an
already exisiting one - I prefix each uploaded file with time() timestamp.
Something like:
$unique_id = time();

Then when I give the new name to move the file to, I use something like:
$unique_id."-".$filename

So I get a fairly unique filename each time a file is uploaded. Obviously,
if two files are uploaded at once, both will have the same timestamp, but
I don't worry too much about that. Hope this might help someone.


08-May-2002 11:06

Here is a fully functional File Upload Handler function. You simply pass it
the name that you typed on the form, the upload dir (and others if your
advanced,) and viola!

call like so:
$OkExt = Array('php', 'htm', 'html')
DoFileUpload('Userfile', 1024, './upload', '', $OkExt , '', '') 

$ForceFilename is if you want to use this name instead of whats in the
$_FILES var.

$Overwriteok - set to anything but '' for yes

$ErrorFunction - set to the name of a function you defined, or '' to use
default.

Need help? ask again.
Not that you may have to fix word wrap...

----------------------------
function DoFileUpload($InputFile, $MaxSize, $Path, $ErrorFunction,
$ExtsOk, $ForceFilename, $OverwriteOk) {
//Copyright CBWhiz
	$ErrNo = -1;
	$TempFile = $_FILES[$InputFile]['tmp_name'];
	$FileSize = $_FILES[$InputFile]['size'];
	$FileName = $_FILES[$InputFile]['name'];
	$FileType = $_FILES[$InputFile]['type'];
	if (strlen($ForceFilename)) { $FileName = $ForceFilename; }

if (!function_exists($ErrorFunction)) {
	if (!function_exists('DoFileUploadDefErrorHandle')) {
		function DoFileUploadDefErrorHandle($ErrorNumber, $ErrorText) {
			echo "<center><font color=red><b>Error
$ErrorNumber: $ErrorText</b></font></center>";
		}
	}
	$ErrorFunction = 'DoFileUploadDefErrorHandle';
}

	echo <<<HTML
<hr>
<center>Uploading $InputFile:<hr width=35%> <table> <tr><td>Filename:</td><td>$FileName</td></tr> <tr><td>File Size:</td><td>$FileSize</td></tr> <tr><td>Temporary File:</td><td>$TempFile</td></tr> <tr><td>File MIME Type:</td><td>$FileType</td></tr> </table> <hr width=35%> </center> HTML; if($TempFile == 'none' || $TempFile == '') { $ErrorTxt = "This File was unspecified."; $ErrNo = 1; $ErrorFunction($ErrNo, $ErrorTxt); return $ErrNo; } if(!is_uploaded_file($TempFile)) { $ErrorTxt = "File Upload Attack, Filename: \"$FileName\""; $ErrNo = 2; $ErrorFunction($ErrNo, $ErrorTxt); return $ErrNo; } //if(!is_uploaded_file($TempFile)) if($FileSize == 0) { $ErrorTxt = 'The file you attempted to upload is zero length!'; $ErrNo = 3; $ErrorFunction($ErrNo, $ErrorTxt); return $ErrNo; } //$FileSize == 0 $TheExt = GetExt($FileName); foreach ($ExtsOk as $CurNum => $CurText) { if ($TheExt == $CurText) { $FileExtOk = 1; } } if($FileExtOk != 1) { $ErrorTxt = 'You attempted to upload a file with a disallowed extention!'; $ErrNo = 4; $ErrorFunction($ErrNo, $ErrorTxt); return $ErrNo; } if($FileSize > $MaxSize) { $ErrorTxt = 'The file you attempted to upload exceeded the maximum file size of' . ($MaxSize / 1024) . 'kb.'; $ErrNo = 5; $ErrorFunction($ErrNo, $ErrorTxt); return $ErrNo; } //if($FileSize > $MaxSize) if(file_exists($Path.$FileName) && !strlen($OverwriteOk)) { $ErrorTxt = 'The file you attempted to upload already exists. Please specify a new filename.'; $ErrNo = 6; $ErrorFunction($ErrNo, $ErrorTxt); return $ErrNo; } //----------------------------------- //-------Actual Uploading Here move_uploaded_file ($TempFile, $Path.$FileName); chmod ($Path.$FileName, 0644); //Remove if your webserver hates you :D echo '<center>File Upload Sucess!</center>
'; return $ErrNo; } //function DoFileUpload($InputFile, $MaxSize, $Path, $ErrorFunction, $ExtsOk, $ForceFilename, $OverwriteOk) function GetExt($Filename) { $RetVal = explode ( '.', $Filename); return $RetVal[count($RetVal)-1]; }


12-May-2002 05:04

Guys here,I think u should take a look here:
Array ( [attach] => Array ( [name] => An01_019.gif [type] =>
image/gif [tmp_name] => [error] => 2 [size] => 0 ) ) 
I use a file upload with max_file_size,I found here is a error,what does
it mean.

And I also found this:
If u file size is larger than the max_file_size error would be 2,and if
there is no file upload ,error would be 4, if the file uploaded
correctly,error is 0.
But my Question is when it would be 3?


28-May-2002 07:41

Somebody asked for the error codes for the $_FILES error variable. I just
found them in the code...

#define UPLOAD_ERROR_A  1  /* Uploaded file exceeded upload_max_filesize
*/
#define UPLOAD_ERROR_B  2  /* Uploaded file exceeded MAX_FILE_SIZE */
#define UPLOAD_ERROR_C  3  /* Only partiallly uploaded */
#define UPLOAD_ERROR_D  4  /* No file uploaded */
#define UPLOAD_ERROR_E  5  /* Uploaded file size 0 bytes */


07-Jun-2002 01:39

Hi,

To get the max upload filesize i use this

<?php

  echo get_max_upload();

  function get_max_upload() {
    if (!ini_get("file_uploads")) {
      return FALSE;
    }
    $upload_max_filesize =
get_real_size(ini_get("upload_max_filesize"));
    $post_max_size = get_real_size(ini_get("post_max_size")); //

 User Contributed Notes - [email protected]
    $memory_limit = round(get_real_size(ini_get("memory_limit"))
/ 2); // 
 User Contributed Notes - [email protected]
    if ($upload_max_filesize>$post_max_size) {
      $max = $post_max_size;
    } else {
      $max = $upload_max_filesize;
    }
    if (($memory_limit!="")&&($memory_limit<$max)) {
// i had problems to get the "memory_limit" from the php.ini
(this is testing on winXP with apache)
      $max = $memory_limit;
    }
    return $max;
  }

  function get_real_size($size) {
    if ($size=="") { return 0; }
    $scan['MB'] = 1048576;
    $scan['M'] = 1048576;
    $scan['KB'] = 1024;
    $scan['K'] = 1024;
    while (list($key) = each($scan)) {
      if ((strlen($size)>strlen($key))&&(substr($size,
strlen($size) - strlen($key))==$key)) {
        $size = substr($size, 0, strlen($size) - strlen($key)) *
$scan[$key];
        break;
      }
    }
    return $size;
  }

?>


07-Jun-2002 07:39

It should be noted that there is a control for file uploads in PHP.INI
which must be on for any of this to work. In fact, my experience is that
if file uplods are turned off in php.ini, NONE of the fields in a
multipart/form-data form will be passed to PHP. This will be truw whether
or not a file is being uploaded.


08-Jun-2002 12:25

I was having problems with the returned upload array. The name, and type
were returned, but tmp_name was empty and size was set as 0.

I removed the maxfilesize input type, and it worked perfectly again, all
of the elements of the array were present. Odd but true. Hope this helps
someone out.

12-Jun-2002 08:21
this is really wierd, wanted to let y'all know that I tried many upload
scripts could not make any work until I set "register_globals = on
". I was trying to avoid turning it on b/c of all the security
warnings but it was unavoidable.
Im running win2k, apache 2.0.36 and php 4.2.1. I used the recommended
php.ini which already had  "file_uploads = on" and I set
an"upload_tmp_dir". Now ...I could not install php as a module
(dont ask me why Im happy its working) I had to use the CGI
binary,php.exe. could this be a problem?

Bottom line I got my stuff working but if there is a better way Im all
ears.


14-Jun-2002 05:29

Dave has a good upload class working with 4.2.1 


18-Jun-2002 05:32

I had a strange Problem on a Debian System with PHP 4.2.1-3.

$filename is $filename_name not the tempname on the Server.

--- CUT ---

if ($filename==$filename_name):
    $filename=$_FILES['filename']['tmp_name'];
endif;

--- CUT END ---

This bit of code helps to get the right tempfile as u expect.

prof_

18-Jun-2002 09:40
Si trabajas en XP, es necesario colocar los slashes de esta forma:

"e:/inetpub/wwwroot/vfc/fotosup\\".$userfile_name


21-Jun-2002 05:30

One important point to note is that there is a upload parameter in the php
configuration file (i.e. php.ini). There is a section called "File
Uploads". 

If large files would be uploaded to the server,  upload_max_filesize
should be set to a large size. e.g. 10M


24-Jun-2002 07:24

I've pieced this together out of bits I've found elsewhere, but the info
belongs here.

If you're on a shared host that won't allow you to modify the php.ini file
and your max_upload_size is set low, you can create an .htaccess file in
the upload handler script directory that contains:

php_value upload_max_filesize 8000000

(example set for 8 megs)

As a nice side benefit, it will keep big uploads from being erroneously
listed as an upload attack via many of the scripts found here ;)


29-Jun-2002 05:54

Always use move_uploaded_file() to have your uploaded file in a suitable
location, not copy() .

move_uploaded_file() is easier and more secure.

And it will work in safe_mode and with an open_basedir.

It your customers complain about errors like :

Warning: open_basedir restriction in effect. File is in wrong directory in
/users/sexydoo/www.bitchy-sex.com/html/inscription.php on line 40

with scripts managing uploaded files, tell them to replace copy() calls
with move_uploaded_file() .

add a note about notes
previousCookiesErreurs classiquesnext
Last updated: Tue, 11 Jun 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat Jul 6 20:06:19 2002 CEST