Contents / Previous / Next


Handling File Uploads

A file upload screen can be built by creating a special form which looks something like this ("upload.html"): <html><body> <form enctype="multipart/form-data" action="upload.php" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="30000"> Send this file: <input name="userfile" type="file"> <input type="submit" value="Send File"> </form> </body></html> 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).

The $_FILES arrays will contain all your uploaded file information (assuming the file upload name "userfile", as used in the from above):

$_FILES['userfile']['name']
  The original name of the file on the client machine.

$_FILES['userfile']['type']
  The mime type of the file.

$_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.


The action field in the HTML form should point to a PHP file ("upload.php") that will process the uploaded file:

<? // Confige PHP to allow file uploads // and provide it with a directory with // public write permissions to store to // uploaded tmp files. ini_set (\"file_uploads\",\"1\"); ini_set (\"upload_tmp_dir\", \"/tmp/\"); $uploaddir = '/tmp/'; $tmp_file = $_FILES['userfile']['tmp_name']; $file = $_FILES['userfile']['name']; if (move_uploaded_file( $tmp_file, $uploaddir.$file )) { print "File is valid, and was successfully uploaded. Here's some more debugging info:<P>"; print_r($_FILES); } else { print "Possible file upload attack! Here's some debugging info:<P>"; print_r($_FILES); } ?> Uploaded files are stored in the server's default temporary directory, you should either delete the file from the temporary directory or move it elsewhere.

bool move_uploaded_file ( string filename, string destination): Moves an uploaded file to a new location.
If the file is valid (meaning that it was uploaded via PHP's HTTP POST upload mechanism), it will be moved to the filename given by destination.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

bool is_uploaded_file ( string filename): Returns TRUE if the file named by filename was uploaded via HTTP POST.
This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

Configuration: You may have to configure some PHP parameters to enable file uploading, you can do that at the top of your upload script:

$uploaddir = "/home/fred/public_html/"; ini_set ("upload_tmp_dir", $uploaddir); ini_set ("file_uploads", "1");