How to validate files using MIME?

ajax, javascript, jquery, php

Solution

MIME type lookup is usually pretty fast, and in PHP you can do it with the `finfo` extension. Example:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, '/path/to/file.jpg'); // image/jpeg
finfo_close($finfo);

Also, you shouldn't rely on the `type` index of the `$_FILES` superglobal, as that value can be spoofed to anything an attacker may want. Same thing goes for the file extension of course.

Problem

I want to validate file types in server using php. Now at the moment I have validated it by checking the file extension type of the file. This works fines but the problem is that this isn't the best way to validate the file as a user an change lets say a text file into a jpeg and still be able to upload it. So what I want to do is add another validation method, I also want to check the file's MIME type using php to recognize if the file is a image, video or audio. So my question is how is it coded so that I can use MIME type in php to be able to validate a file? Also if I have an extremely large file, does it take a long time for the MIME validation to kick in or does it validate straight away? Below is currently the code I have for Image only where it uses php code to check for file type: ``` <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; } } else { echo "Invalid file"; } ?> ```

Original source