- Upload files and directories using an input, drag and drop, or copy and paste with HTML5
- #Basic file input
- #Drag and drop files
- #Paste file
- How to upload a file using PHP.
- The HTML upload form.
- The PHP upload script.
- The upload directory.
- Checking the file extension.
- The $_FILES array.
- The $_FILES array explained.
- The move_uploaded_file function is safe.
- Html upload file to directory
- Answered by:
- Question
- Answers
Upload files and directories using an input, drag and drop, or copy and paste with HTML5
Many websites have a form to upload a file. For some sites, such as OneDrive or Google Drive, uploading files is a major feature. As time went on, webpages are more and more interactive. So, users expect more interactions such as dragging and dropping files or directories or pasting screenshots.
Let’s see what browsers provide to upload files!
#Basic file input
The basic way is by using a form and an input with the file type:
- multiple : allows multiple files to be selected
- accept : choose expected mime types, for instance: image/* , application/pdf
#Drag and drop files
Most users expect to be able to drag and drop files on the page. This functionality is well-supported by browsers and very easy to implement. Once you get the files, you need to do something such as uploading them to an API or read their content using the FileReader api.
document.body; dropZone.e) < e.classList.); dropZone.e) < e.classList.); dropZone.e) < e.classList.); dropZone.e) < e.classList.dataTransfer.files); console. >); >
You can easily upload files to an API using the fetch API :
length > 0) < ) .() => console.)) .reason => console.
Google Chrome and Microsoft Edge now support dropping directories. This is very useful when you want to upload your files to OneDrive or Google Drive. The API is not very convenient as it uses callback functions with a recursive tree, but it’s not that hard. Let’s see some code:
dropZone.e) < e.classList.console.dataTransfer: DataTransfer) < 0; i < dataTransfer.items.length; i++) < items[i]; kind === webkitGetAsEntry === > > entry: FileSystemEntry) < (resolve, reject) => < 0; entry: FileSystemEntry) < file => < reading--; contents.0) < >); > > reader: FileSystemDirectoryReader) < reading++; reader.entries) < reading--; 0) < >); > >); > entry: FileSystemEntry): entry is isDirectory; > entry: FileSystemEntry): entry is isFile; >
The webkitGetAsEntry function also works in Microsoft Edge.
#Paste file
Currently, you can only paste images, not image files nor any other types of file. This may change in the future, but at the moment this is enough to upload screenshots. I often paste images when creating an issue on JIRA or VSTS 😃
Supporting image pasting is a quick win because you can reuse the previous code. Indeed, you can simply handle the paste event and use the previous getFilesAsync function:
e) < e.clipboardData); console.You are now masters in uploading files and directories using all the possible ways your browser support (at the time of writing)!
Do you have a question or a suggestion about this post? Contact me!
How to upload a file using PHP.
This is a tutorial on how to upload a file using PHP. In this article, we will create two things:
- The HTML form that will allow the user to select a file to upload.
- The PHP script that will receive the uploaded file, validate it, and then move it to a directory of our choosing.
Let’s start off by creating the HTML form.
The HTML upload form.
Take a look at the following HTML form:
There are a few important things to note about the form above:
- The enctype attribute on our form element has been set to multipart/form-data. This is extremely important, as our upload form will not work without it. By setting this attribute to multipart/form-data, we are telling the browser that it should notencode the form data.
- The action attribute has been set to upload-script.php. As a result, our HTML form will submit the uploaded file to upload-script.php. i.e. This is the PHP script that we will need to create in order to manage our file upload.
- We set the method attribute to post. This is also extremely important, as it tells our browser that we want to send a POST request. If we fail to set this attribute, the form will send the data as a GET request and our file will not be uploaded.
- We created an input element with type=”file” and named it user_file. This is the form element that the user can click on in order to select a file from their file system.
- Finally, we created a simple submit button.
If you view this form in your browser, you will see that it looks pretty basic:
A screenshot of our upload form.
If you choose a file and submit it, you will probably receive a 404 Not Found error for upload-script.php. This is because the PHP file that will handle our upload doesn’t exist yet.
The PHP upload script.
In our HTML form above, we set the action attribute to upload-script.php. Now we will need to create that file and insert some PHP code to handle our upload.
Take a look at the following script, which I have heavily commented:
//The folder that our file should be moved to //once it is uploaded $uploadDirectory = 'uploads/'; //If our uploaded file exists. if(isset($_FILES['user_file'])) < //The extensions that are allowed to be uploaded. $allowedExtensions = array( 'png', 'jpg', 'jpeg', 'csv', 'xls' ); //Get our file details from the $_FILES array. $file = $_FILES['user_file']; //The name of the file that has been uploaded. //Example: image.png or data.csv //This is what the user named it. $name = $file['name']; //Get the extension of the file. $extension = pathinfo($name, PATHINFO_EXTENSION); //Force the file extension into a lower case. $extension = strtolower($extension); //If it isn't a valid extension. if(!in_array($extension, $allowedExtensions))< //Print out a message to the user. echo 'That extension is not allowed!'; >else < //If it is a valid extension, move it to our uploads directory. //The current / temporary location of the uploaded file. //We will need to move it from here to our uploads directory. $tmpLocation = $file['tmp_name']; //The location that we want to move the uploaded file to. $newLocation = $uploadDirectory . $name; //Move the file using PHP's move_uploaded_file function. $move = move_uploaded_file($tmpLocation, $newLocation); >>
There are a few important things to note about the PHP code above.
The upload directory.
At the top of our PHP script, we set the $uploadDirectory to uploads/. This is the location where our uploaded files will be moved to if the upload is successful. Note that this can be a relative path or an absolute path.
An example of an absolute path:
//Absolute path to our uploads directory. $uploadDirectory = '/var/www/html/uploads/';
You can also use a relative path to reference a folder in the parent directory:
//Relative path to a folder called uploads in //the parent directory $uploadDirectory = '../uploads/';
Currently, our upload-script.php assumes that it is located in the same directory as the uploads folder.
Checking the file extension.
Using a PHP array called $allowedExtensions, we created a whitelist of valid file extensions. This is for security purposes. For example, what if a hacker decided to upload a PHP file?
That would lead to disastrous results, as you’d be giving them free reign to execute their PHP code on your server.
Note that you should feel free to add or remove extensions from this array to suit your own needs. However, I would strongly suggest that you do not remove this file extension check completely.
The $_FILES array.
The $_FILES array is a superglobal array that contains information about any files that have been uploaded to the server. In the code above, we were able to get the details of our uploaded file by using the name of the file input in our HTML form:
//Get our file details from the $_FILES array. $file = $_FILES['user_file'];
If you take another look at our HTML form, you will see that we gave our upload field the name user_file. As a result, you will need to use that name in order to retrieve the file’s details from the $_FILES array.
Below is a screenshot of a var_dump of the file’s details: