Handling File Uploads With PHP
DiggBlinkRedditDeliciousTechnorati
article by Srirangan
This is a minimalistic guide on how to handle file uploads using PHP and XHTML forms. Prerequisites are basic XHTML and PHP skills.
Step 1: Creating an XHTML form
A form needs to be created through which a user can select the file that needs to be uploaded and pass it on to the PHP script which uploads the file. It's a very simple form using the "input type=file" attribute.
<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>
Step 2: Processing the upload
Now comes the PHP part. The approach I use here is to make use of the move_uploaded_file() and the global $_FILES variable.
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if ( is_uploaded_file($_FILES['userfile']['tmp_name']) && move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile) ){
echo "File is valid, and was successfully uploaded.
";
} else {
echo "Possible file upload attack!
";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Notes
- Provide your file with sufficient permissions, ie. the requisite write permissions in your operating system
- Modify the $uploaddir variable suitably to point to the writable folder where you want to save the uploaded files
References
[1] PHP Documentation