File upload functionality in PHP

File uploading is one of the most popular topics every budding PHP developer eagerly wants to explore as to what would be the best possible approach to achieve it.

File uploading is a very basic requirement that we come across in most of the web applications is to integrate file upload functionality. Demonstrated below is an approach on how we can implement it, but we need to be very careful doing it with proper validations.

If the file uploading is not properly validated, we might implant a serious security flaw in our application, where a malicious file might get uploaded on the server if not properly validated.

Before we start, we must make sure we have the DB table (we chose to name it as tbl_uploads) ready to add appropriate entries whenever a file is uploaded. The DB table structure should look like –

File Uploadng in PHP

Now let’s create the HTML interface for file uploading –

Note that we have specified file upload form action to be upload.php, let’s now create the file as –

Let’s now create a view.php file that displays the list of uploaded files along with the link to the same.

There are few points that needs to be taken care of –

  1. Ensure that your server allows file upload. Verify the file_uploads attribute in php.ini file. php.ini can be found in the server root directory. If you do not find it, please contact your server administrator for the same.
  2. Proper validation must be done for a secure file upload functionality like –
    1. Restrict the type of files that can be uploaded.
    2. Limit the file size.

Usually the file type check with $_FILES[‘file’][‘type’] is a bad option. Rather using PHP functions like exif_imagetype is a better option, which also checks for the information contained within the file.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.