PHP | Uploading File
Have you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with – ‘Are we able to upload any kind of file with this system?’. The answer is yes, we can upload files with different types of extensions.
HTML code snippet: Below is the HTML source code for the HTML form for uploading the file to the server. In the HTML <form> tag, we are using “enctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form.
Now, time to write a PHP script which is able to handle the file uploading system. file-upload-manager.php
In the above script, once we submit the form, later we can access the information via a PHP superglobal associative array $_FILES. Apart from using the $_FILES array, many in-built functions are playing a major role. After we are done with uploading a file, in the script we will check the request method of the server, if it is the POST method then it will proceed otherwise the system will throw an error. Later on, we accessed the $_FILES array to get the file name, file size, and type of the file. Once we got those pieces of information, then we validate the size and type of the file. In the end, we search in the folder, where the file is to be uploaded, for checking if the file already exists or not. If not, we have used move_uploaded_file() to move the file from the temporary location to the desired directory on the server and we are done.