Monthly Archives: June 2013

Uploaded File – Check File Type (PHP)

Recently, I found an issue with checking a file’s type while using the simple upload form. After some investigation I found why the code for checking a file’s extension type wasn’t working as well as an alternative to solve the problem.

Here’s the code for the form I used:

For simplicity, I got this sample of PHP code from here.

Now, usually I would use the $_FILES array to test a file’s type during processing to decide whether to accept or reject the file but the $_FILES[“filename”][“type”] result (even though correct) would not respond to my request as planned.

The hint (in regards to $_FILES[“filename”][“type”]) I found was on php.net website which states the following: “The mime type of the file, if the browser provided this information. An example would be “image/gif”. This mime type is however not checked on the PHP side and therefore don’t take its value for granted.”

So, an alternative solution to this is to retrieve the file’s full name including extension using $_FILES[“filename”][“name”], explode the name using a period ( . ), and lastly use the last piece of array (which is the resulting extension) to match it with what you want. Here’s a sample of the working code:

I hope this helps. Enjoy it.