Uploading Files with PHP
Very often you will want users to able to upload files to your server. This is easily accomplished using a smattering of PHP code.
File Upload Form
The following is an example file upload form.
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="userfile" type="file" />
<input type="submit" value="Upload File" />
</form>
The hidden MAX_FILE_SIZE field contains the maximum file size accepted, in bytes. This cannot be larger than upload_max_filesize in php.ini (default 2MB). Note also that this hidden field must precede the file input field in the HTML. This field is only advisory to the browser and is easy to
circumvent.
Handling Uploaded Files with PHP
PHP stores all the uploaded file information in the $_FILES autoglobal array.
$_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.
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.
Use moveuploadedfile() to store an uploaded file somewhere permanently.
PHP Code
Here is some example PHP code for handling and validating a file upload.
<?php
$uploadDir = '/var/www/uploads/';
$uploadFile = $uploadDir . $_FILES['userfile']['name'];
print "<pre>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile)) {
print "File is valid, and was successfully uploaded. ";
print "Here's some more debugging info:";
print_r($_FILES);
} else {
print "Possible file upload attack! Here's some debugging info:";
print_r($_FILES);
}
print "</pre>";
?>
PHP Manual
As always, check the excellent PHP manual for more information on handling file uploads.