You may want visitors to your website to upload their profile pictures and other documents like pdf or just share files on your website for the public to download. However, your ability to handle file uploads can be advantageous to your website.
The ability to upload files lies in HTML input element type ‘file’, which brings up a dialog box that allows your visitor to select a file for upload. This element is part of the form elements. Web browsers render it as a TextBox, a select Or browse button. When your visitors submit the form, the form input type ‘file’ is also submitted with it, hence, uploading the file to your server.
Let’s try our hands on a sample HTML form that allows visitors to your website to upload any file they choose to your server.
<form enctype="multipart/form-data" method="POST" action="index.php"> Select File:<input name="filename" type="file"> <input type="submit" name="submit" value="Upload"> </form>
Select File:
Note that the HTML Form has an enctype to allow us to upload files properly and the action property of the form is set to post the form to the index.php page.
The PHP Part
The PHP code below check to see if the form is submitted and if it is true it prints the name and size of the file your visitor has uploaded.
<?php if(isset($_POST["submit"])){ print "Received {$_FILES['filename']['name']} - Its Size Is {$_FILES['filename']['size']}"; } ?>
According to php.net the function below
bool move_uploaded_file ( string $filename , string $destination )
This function checks to ensure that the file designated by filename is a valid Upload File (meaning that it was uploaded via PHP’s HTTP POST Upload Mechanism). If the file is valid, it will be moved to the filename given by
destination
.This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
By default, the uploaded files are stored in a temporary place on the server, which means that you have moved the uploaded files to a folder of your choice.
The PHP code below can be used to move the uploaded files to appropriate location on your server.
<?php if (move_uploaded_file($_FILES['filename']['tmp_name'], "/path/to/upload/folder")) { print "Received {$_FILES['filename']['name']} - Its size is {$_FILES['filename']['size']}"; } else { print "Upload Failed!"; } ?>
Finally, you need to give the right permission to PHP to move the file “/path/to/upload/folder”.
No Comments
Leave a comment Cancel