Uploading files with PHP

Create a form to upload to your PHP script, something like:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

Change “URL” in the example above to the name of the PHP script which will receive the uploaded file, for example upload.php.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted. This is an advisory to the browser, PHP also checks it. Fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. The PHP settings for maximum-size, however, cannot be fooled. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too big and the transfer failed.

Some example code to show how the upload works:

print "<pre>";
 
foreach $field (array('name','type','size','tmp_name','error')) {
    printf("%s is %s\n", $field, $_FILES['upfile'][$field];
}

The output will look like:

name is badger2.gif
type is image/gif
size is 14282
tmp_name is /tmp/phpPI3ymK
error is 0

For further illustration:

print_r($_FILES);
// will print something like:
Array
(
    [upfile] => Array
        (
            [name] => badger2.gif
            [type] => image/gif
            [tmp_name] => /tmp/phpTfcSta
            [error] => 0
            [size] => 14282
        )
 
)

Moving uploaded file to desired directory

Now, to move the uploaded file to wherever you want it stored:

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
 
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
   echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Failed to move uploaded file to desired directory\n";
}

If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

~~DISCUSSION~~

 
php/uploadfile.txt · Last modified: 2010/02/26 10:45 (external edit)
 
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki