views:

1248

answers:

4

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.

A: 

The main benefit of Flash is it allows you to upload multiple files. The main benefit of Java is it allows drag-and-drop from the file system. Sorry for not answering the central question, but I thought I'd throw that in as it's fairly simple.

eyelidlessness
Hey, that's good information to have. +1.
Abyss Knight
An additional benefit is that in PHP 4 you can't show an upload progress bar. You can in PHP 5, Flash and Java.
David
Instead of talking about Java and Flash, it would be much more useful if you gave the example code that shows how the progress bar would be shown using PHP5 ;)
Milan Babuškov
You can. http://www.phpclasses.org/blog/post/61-File-upload-progress-meter-for-PHP-4-at-last.html
eyelidlessness
+3  A: 

Have a read of this introduction which should tell you everything you need to know. The user comments are fairly useful as well.

Ross
+14  A: 

File Upload Tutorial

HTML

<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" />
</form>
  • 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. It's 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).

PHP

<?php
$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_r($_FILES);
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:

    Array
    (
        [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 PHP.net manual.

Drew Noakes
Worth noting that in that example I could upload a php file and gain access to your web server. Be careful with that stuff. :S
Paolo Bergantino
Right you are. I posted this as a community answer, so feel free to edit it yourself :)
Drew Noakes
Yes, checking the mimetype of files you upload is important. Best protection is to allow certain types (image/jpeg, archive/zip etc.) and disallow all others.
Ross
@Ross: That sounds like a good idea. Can you demonstrate some code for checking MIME types? Thanks for the link, btw.
Drew Noakes
I use the FileInfo extension for checking MIME types. Added to this post (as it's better) and changed the formatting a little.
Ross
Nice updates Ross, thanks. I learned some Markdown from you as well.
Drew Noakes
+2  A: 

Security is a pretty big thing with regards to file uploads, adding a .htaccess to the uploads folder which stops scripts being run from it could be handy to add just an extra layer of security.

.htaccess

Options -Indexes
Options -ExecCGI
AddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi

Reference: http://www.mysql-apache-php.com/fileupload-security.htm

cole