PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previousCookiesError Messages Explainednext
Last updated: Thu, 18 Jul 2002
view this page in Printer friendly version | English | Chinese | Czech | Dutch | Finnish | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

Cap�tulo 20. Handling file uploads

POST method uploads

PHP is capable of receiving file uploads from any RFC-1867 compliant browser (which includes Netscape Navigator 3 or later, Microsoft Internet Explorer 3 with a patch from Microsoft, or later without a patch). This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.

Related Configurations Note: See also the file_uploads, upload_max_filesize, upload_tmp_dir, and post_max_size directives in php.ini

Note that PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.

A file upload screen can be built by creating a special form which looks something like this:

Exemplo 20-1. File Upload Form

<form enctype="multipart/form-data" action="_URL_" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000">
Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
The _URL_ should point to a PHP file. The MAX_FILE_SIZE hidden field must precede the file input field and its value is the maximum filesize accepted. The value is in bytes.

Aten��o

The MAX_FILE_SIZE is advisory to the browser. It is easy to circumvent this maximum. So don't count on it that the browser obeys your wish! The PHP-settings for maximum-size, however, cannot be fooled.

The Variables defined for uploaded files differs depending on the PHP version and configuration. The autoglobal $_FILES exists as of PHP 4.1.0 The $HTTP_POST_FILES array has existed since PHP 4.0.0. These arrays will contain all your uploaded file information. Using $_FILES is preferred. If the PHP directive register_globals is on, related variable names will also exist. register_globals defaults to off as of PHP .

The contents of $_FILES from our example script is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above.

$_FILES['userfile']['name']

The original name of the file on the client machine.

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif".

$_FILES['userfile']['size']

The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']

The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']

The error code associated with this file upload. ['error'] was added in PHP 4.2.0

Nota: In PHP versions prior 4.1.0 this was named $HTTP_POST_FILES and it's not an autoglobal variable like $_FILES is. PHP 3 does not support $HTTP_POST_FILES.

When register_globals is turned on in php.ini, additional variables are available. For example, $userfile_name will equal $_FILES['userfile']['name'], $userfile_type will equal $_FILES['userfile']['type'], etc. Keep in mind that as of PHP 4.2.0, register_globals defaults to off. It's preferred to not rely on this directive.

Files will by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.

Exemplo 20-2. Validating file uploads

The following examples are for versions of PHP 4 greater than 4.0.2. See the function entries for is_uploaded_file() and move_uploaded_file().

<?php 
// In PHP earlier then 4.1.0, $HTTP_POST_FILES  should be used instead of $_FILES.
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    copy($_FILES['userfile']['tmp_name'], "/place/to/put/uploaded/file");
} else {
    echo "Possible file upload attack. Filename: " . $_FILES['userfile']['name'];
}
/* ...or... */
move_uploaded_file($_FILES['userfile']['tmp_name'], "/place/to/put/uploaded/file");
?>

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can for example use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria. As of PHP 4.2.0, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

User Contributed Notes
Handling file uploads
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() .


14-Jul-2002 05:53

Well, it could look so obvious, but I spent some hour asking to myself why
the hell the whole thing didn't work: when I sent POST with
ENCTYPE="multipart/form-data", I did find the file uploaded into
/tmp, but the post data were completely BLANK!! The matter was that the
php.ini file actually has a file_uploads directive, and in my Red Hat 7.3
distro it is Off by default.


19-Jul-2002 04:57

--HANDLING LARGE FILE UPLOADS and entering into a MySQL blob field--

Hope this helps someone as it was a bitch to fig out.  MySQL default
buffer and packets are set small.  here is a method to get aroudn it.

$filehandle = fopen($addfile, "r");
$filesize = filesize($addfile);

//now this is bullshit, but have to read the file piece by piece and
insert because the mysql server is set up to only handle 1meg inserts
(small buffer and packet).

$buffer = addslashes(fread($filehandle, 906240));
$query = "Insert into files (file, filename, size, userid ) values
('$filedata','$addfile_name', '$filesize')";
$this->query($query);
$id = mysql_insert_id($this->link_id());
	 	
while (!feof ($filehandle)) {
  $buffer = addslashes(fread($filehandle, 906240));
  $query = "UPDATE files SET file = concat('$buffer') where
id='$id'";
  $this->query($query);
}
fclose ($filehandle);

add a note about notes
previousCookiesError Messages Explainednext
Last updated: Thu, 18 Jul 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 20 20:16:23 2002 CEST