Processing Uploaded Files






Processing Uploaded Files

Problem

You want to process a file uploaded by a user. For example, you're building a photo-sharing web site and you want to store user-supplied photos.

Solution

Use the $_FILES array to get information about uploaded files. Figure saves an uploaded file to the /tmp directory on the web server.

Uploading a file

<?php if ($_SERVER['REQUEST_METHOD'] == 'GET') { ?>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>"
      enctype="multipart/form-data">
<input type="file" name="document"/>
<input type="submit" value="Send File"/>
</form>
<?php } else {
    if (isset($_FILES['document']) &&
    ($_FILES['document']['error'] == UPLOAD_ERR_OK)) {
        $newPath = '/tmp/' . basename($_FILES['document']['name']);
        if (move_uploaded_file($_FILES['document']['tmp_name'], $newPath)) {
            print "File saved in $newPath";
        } else {
            print "Couldn't move file to $newPath";
        }
    } else {
        print "No valid file uploaded.";
    }
}
?>

Discussion

Starting in PHP 4.1, all uploaded files appear in the $_FILES auto-global array. For each file element in the form, an array is created in $_FILES whose key is the file element's name. For example, the form in Figure has a file element named document, so $_FILES['document'] contains the information about the uploaded file. Each of these per-file arrays has five elements:


name

The name of the uploaded file. This is supplied by the browser so it could be a full pathname or just a filename.


type

The MIME type of the file, as supplied by the browser.


size

The size of the file in bytes, as calculated by the server.


tmp_name

The location in which the file is temporarily stored on the server.


error

An error code describing what (if anything) went wrong with the file upload. (This element is available in PHP 4.2.0 and later versions.)

If you're using a version of PHP earlier than 4.1, this information is in $HTTP_POST_FILES instead of $_FILES.

The possible values of the error element are:


UPLOAD_ERR_OK (0)

Upload succeeded (no error).


UPLOAD_ERR_INI_SIZE(1)

The size of the uploaded file is bigger than the value of the upload_max_filesize configuration directive.


UPLOAD_ERR_FORM_SIZE (2)

The size of the uploaded file is bigger than the value of the form's MAX_FILE_SIZE element.


UPLOAD_ERR_PARTIAL (3)

Only part of the file was uploaded.


UPLOAD_ERR_NO_FILE (4)

There was no file uploaded.


UPLOAD_ERR_NO_TMP_DIR (6)

The upload failed because there was no temporary directory to store the file (available in PHP 4.3.10, 5.0.3, and later).


UPLOAD_ERR_CANT_WRITE (7)

PHP couldn't write the file to disk (available in PHP 5.1.0 and later).

For all of the error values, the listed constants are available in PHP 4.3.0 and later. In earlier versions of PHP, use the number in parentheses next to the constant instead.

The is_uploaded_file( ) function confirms that the file you're about to process is a legitimate file resulting from a user upload. Always check the tmp_name value before processing it as any other file. This ensures that a malicious user can't trick your code into processing a system file as an upload.

You can also move the file to a permanent location; use move_uploaded_file( ), as in Figure. It also does a check to make sure that the file being moved is really an uploaded file. Note that the value stored in tmp_name is the complete path to the file, not just the base name. Use basename( ) to chop off the leading directories if needed.

Be sure to check that PHP has permission to read and write to both the directory in which temporary files are saved (set by the upload_tmp_dir configuration directive) and the location to which you're trying to copy the file. PHP is often running under a special username such as nobody or apache, instead of your personal username. Because of this, if you're running under safe_mode, copying a file to a new location will probably not allow you to access it again.

Processing files can be a subtle task because not all browsers submit the same information. It's important to do it correctly, however, or you open yourself up to security problems. You are, after all, allowing strangers to upload any file they choose to your machine; malicious people may see this as an opportunity to crack into or crash the computer.

As a result, PHP has a number of features that allow you to place restrictions on uploaded files, including the ability to completely turn off file uploads altogether. So if you're experiencing difficulty processing uploaded files, check that your file isn't being rejected because it seems to pose a security risk.

To do such a check, first make sure file_uploads is set to On inside your configuration file. Next, make sure your file size isn't larger than upload_max_filesize; this defaults to 2 MB, which stops someone from trying to crash the machine by filling up the hard drive with a giant file. Additionally, there's a post_max_size directive, which controls the maximum size of all the post data allowed in a single request; its initial setting is 8 MB.

From the perspective of browser differences and user error, if you don't see what you expect in $_FILES, make sure you add enctype="multipart/form-data" to the form's opening tag. PHP needs this to process the file information properly.

Also, if no file is selected for uploading, versions of PHP prior to 4.1 set tmp_name to none; newer versions set it to the empty string. PHP 4.2.1 allows files of length 0. To be sure a file was uploaded and isn't empty (although blank files may be what you want, depending on the circumstances), you need to make sure tmp_name is set and size is greater than 0. Last, not all browsers necessarily send the same MIME type for a file; what they send depends on their knowledge of different file types.

See Also

Documentation on handling file uploads at http://www.php.net/features.file-upload and on basename( ) at http://www.php.net/basename .



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows