Saturday, February 22, 2014

Validating file extension in PHP

While making a file uploading or sharing system many do mistakes while adding the extension checking functionality and because of that many users are able to upload vulnerable files such as upload a PHP or Javascript or any other file. To prevent it what we do is to make a list of allowed extensions. When the user will upload the file then we'll retrieve the file extension and check whether that file extension is in our list or not. This makes a beautiful layer of security and it's important to do it.

What mistakes many do?
The mistakes what many people do is to check the MIME type. It's not recommended to compare the MIME type. Because MIME type can be changed.
For example, let's take that a user has uploaded a PHP file which contains some terrible code that can produce a DDOS attack on your website. So if he has successfully uploaded that file and shared the URL to access it. If 10 users click on the same URL, then probably your website will go down. This will happen because of the server got crashed or if your host is strict against bandwidth then obviously the host will shut your website down.

What's the best option to protect against this problems?
The best option is to add a file extension check. So whenever a user tries to upload any file our script will first check for the extension. If the extension is in the list then the file can go for other checks like size etc. But if it's not in the list then we'll show an error to the user to notify him about it.

Live Demo Download Now

Here's the function:


Example usage:

1 comment:

  1. this is what i was looking for,

    ReplyDelete

Your Comment Will Be Visible After Approval, Thanks !