Monday, 19 May 2014

PHP Check Mime Type of File - Return Information About A File

Now a days, we are uploading files like Profile images, Video files OR excel files in our web application. With uploading these files there are chances some user upload the .exe file (Virus) by renaming the .exe into .jpg, which can damage website.

You might have added the extension check from javaScript as well as PHP. But this is not enough from security end because someone can upload the file after changing the extension of file( ".exe" to ".png"). In this case your security check will be failed.

What to do.
Answer is check the Mime of file before get uploaded in your web server.

How to do this
"fileinfo" is extension which must be enabled in your php.ini. (for existence you can check in phpinfo)
If this extension is not enabled ask your server admin, he will do this for you OR you can also do this your self (http://php.net/manual/en/fileinfo.installation.php).

After installing the fileinfo extension, use following code to get the mime type of file before get uploaded in web server.

When you execute above code, if will get the mime-type of file. This is directly checking the mime type of already uploaded file.
You can use $type = finfo_file($finfo,$file); for checking the file type, before using move_uploaded_file function.