Thursday, March 12, 2009

PHP - File Upload

Want to create something like this?
Choose a file to upload:

PHP Solution: (Source: http://www.tizag.com/phpT/fileupload.php)

What to include in your HTML Form:

<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>

Points to note:
1) The form type must be "multipart/form-data" in order for the form to process files.
2) MAX_FILE_SIZE attribute determines the maximum file size that can be uploaded.
3) Upon clicking "Upload File" button, data will be posted to the server and uploader.php will handle the processing.

What to include in uploader.php (PHP file that does the "uploading"):

$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
echo "Successful upload!";

else echo "There was an error uploading the file, please try again!";

Points to note:
1) $target_path is the value of where you want to store the uploaded file.
2) $_FILES['uploadedfile'] = file that was posted using the form and has the name 'uploadedfile'.
3) $_FILES['uploadedfile']['name'] = original path of the user uploaded file.
4) $_FILES['uploadedfile']['tmp_name'] = path to the temporary file that resides in the server.
5) move_uploaded_file function moves the uploaded file from its temporary position to the target path.

Important!
You might want to add more conditions, checks and/or validations before allowing visitors to upload files onto your server. This is to prevent your server from being filled with junk and thus compromising your server's security.

No comments:

Post a Comment