What's The Best Way To Create A Single-file Upload Form Using PHP?

- 1 answer

I've found a few samples online but I'd like to get feedback from people who use PHP daily as to potential security or performance considerations and their solutions.

Note that I am only interested in uploading a single file at a time.

Ideally no browser plugin would be required (Flash/Java), although it would be interesting to know the benefits of using a plugin.

I would like to know both the best HTML form code and PHP processing code.



File Upload Tutorial


<form enctype="multipart/form-data" action="action.php" method="POST">
  <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
  <input name="userfile" type="file" />
  <input type="submit" value="Go" />
  • action.php is the name of a PHP file that will process the upload (shown below)
  • MAX_FILE_SIZE must appear immediately before the input with type file. This value can easily be manipulated on the client so should not be relied upon. Its main benefit is to provide the user with early warning that their file is too large, before they've uploaded it.
  • You can change the name of the input with type file, but make sure it doesn't contain any spaces. You must also update the corresponding value in the PHP file (below).


$uploaddir = "/www/uploads/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "Success.\n";
} else {
    echo "Failure.\n";

echo 'Here is some more debugging info:';
print "</pre>";

The upload-to folder should not be located in a place that's accessible via HTTP, otherwise it would be possible to upload a PHP script and execute it upon the server.

Printing the value of $_FILES can give a hint as to what's going on. For example:

        [userfile] => Array
            [name] => Filename.ext
            [type] => 
            [tmp_name] => 
            [error] => 2
            [size] => 0

This structure gives some information as to the file's name, MIME type, size and error code.

Error Codes

0 Indicates that there was no errors and file has been uploaded successfully
1 Indicates that the file exceeds the maximum file size defined in php.ini. If you would like to change the maximum file size, you need to open your php.ini file, identify the line which reads: upload_max_filesize = 2M and change the value from 2M (2MB) to whatever you need
2 Indicates that the maximum file size defined manually, within an on page script has been exceeded
3 Indicates that file has only been uploaded partially
4 Indicates that the file hasn't been specified (empty file field)
5 Not defined yet
6 Indicates that there´s no temporary folder
7 Indicates that the file cannot be written to the disk

php.ini Configuration

When running this setup with larger files you may receive errors. Check your php.ini file for these keys:

max_execution_time = 30
upload_max_filesize = 2M

Increasing these values as appropriate may help. When using Apache, changes to this file require a restart.

The maximum memory permitted value (set via memory_limit) does not play a role here as the file is written to the tmp directory as it is uploaded. The location of the tmp directory is optionally controlled via upload_tmp_dir.

Checking file mimetypes

You should check the filetype of what the user is uploading - the best practice is to validate against a list of allowed filetypes. A potential risk of allowing any file is that a user could potentially upload PHP code to the server and then run it.

You can use the very useful fileinfo extension (that supersedes the older mime_content_type function) to validate mime-types.

// FILEINFO_MIME set to return MIME types, will return string of info otherwise
$fileinfo = new finfo(FILEINFO_MIME);
$file = $fileinfo->file($_FILE['filename']);

$allowed_types = array('image/jpeg', 'image/png');
if(!in_array($file, $allowed_types))
    die('Files of type' . $file . ' are not allowed to be uploaded.');
// Continue

More Information

You can read more on handling file uploads at the manual.

For PHP 5.3+

//For those who are using PHP 5.3, the code varies.
$fileinfo = new finfo(FILEINFO_MIME_TYPE);
$file = $fileinfo->file($_FILE['filename']['tmp_name']);
$allowed_types = array('image/jpeg', 'image/png');
if(!in_array($file, $allowed_types))
    die('Files of type' . $file . ' are not allowed to be uploaded.');
// Continue

More Information

You can read more on FILEINFO_MIME_TYPE at the documentation.