'PHP $_FILES MIME type returning null

Right now I'm trying to write a script that will only accept certain audio files for upload to a server.

However, some MIME types are being returned as null.

Here is some code fragments:

PHP:

$allowedExt=array('audio/mp4a-latm');
if(isset($_POST))
{
    print_r($_FILES);
    //ToDo: Limit by File Size
    if(in_array($_FILES["fileUpload"]["type"],$allowedExt)){
    echo "file type found";
    }
    else
    echo "wrong file type";
}

HTML:

<form action="php/FileUpload.php" method="POST" enctype="multipart/form-data">
 Choose a file: <input name="fileUpload" type="file" /><br />
 <input type="submit" value="Upload" />
 </form>

The result of the above is:

Array ( [fileUpload] => Array ( [name] => 02 Helix Nebula.m4a [type] => [tmp_name] => <removed for space...>))
wrong file type

From what I understand, type should return the file's MIME type. In this case 'audio/mp4a-latm' for a .m4a file.

If php is properly returning null for .m4a files, then what would be the best approach to ensure I'm actually dealing with audio files? Is there anything more definite than just parsing for the file extensions? (ensure someone hasn't change the extension of say a text document)



Solution 1:[1]

$_FILES['userfile']['type'] - The mime type of the file, if the browser provided this information.

http://www.php.net/manual/en/features.file-upload.post-method.php

That's why this method doesn't work well. You should compare file extension grabbed from

$_FILES['userfile']['name']

with acceptable extensions array (which you should create by yourself)

Solution 2:[2]

If you use php 5.3 or higher you can activate the php file info extension by escaping this line in your php.ini:

extension=php_fileinfo.dll

Then you can get your mime type from the file in php like this:

$pathToFile = 'my/path/to/file.ext';
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($fileInfo, $pathToFile);
finfo_close($fileInfo);

This is more reliable than using what the browser sends you in the $_FILES array from your POST request.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan
Solution 2 Wilt