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
HTML
action.phpis the name of a PHP file that will process the upload (shown below)MAX_FILE_SIZEmust appear immediately before the input with typefile. 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.file, but make sure it doesn’t contain any spaces. You must also update the corresponding value in the PHP file (below).PHP
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
$_FILEScan give a hint as to what’s going on. For example:This structure gives some information as to the file’s name, MIME type, size and error code.
Error Codes
php.iniConfigurationWhen running this setup with larger files you may receive errors. Check your
php.inifile for these keys:max_execution_time = 30upload_max_filesize = 2MIncreasing 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 viaupload_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
fileinfoextension (that supersedes the oldermime_content_typefunction) to validate mime-types.More Information
You can read more on handling file uploads at the PHP.net manual.
For PHP 5.3+
More Information
You can read more on FILEINFO_MIME_TYPE at the PHP.net documentation.