PHP $ _FILES MIME type returning null

I am currently trying to write a script that will only accept certain audio files for upload to the server.

However, some MIME types are returned as null.

Here are some code snippets:

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>

      

Result above:

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

      

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

If php correctly returns null for .m4a files, then what's the best approach to ensure that I am dealing with audio files? Is there something more specific than just parsing files? (make sure someone hasn't changed the extension of the text document)

+3


source to share


4 answers


The MIME element comes from the browser, which means it can be manipulated and therefore not trustworthy.



Either check the extension, or if you really want to, parse the first few bytes of the file to make sure you're expecting it.

+3


source


$_FILES['userfile']['type']

- the type of mime file , if the browser provided this information .

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

This is why this method doesn't work. You have to compare the file extension taken from



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

      

with a valid array of extensions (which you must create yourself)

+1


source


To get the mime type of the file you can use

http://code.google.com/p/filing-cabinet/source/browse/trunk/mime_type_lib.php?spec=svn127&r=127

I have been using it for over 2 years now and it is still a very reliable library.

0


source


If you are using php 5.3 or higher, you can activate the info php file extension by executing this line in php.ini

:

extension=php_fileinfo.dll

      

Then you can get your mime type from 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 is sending you in an array $_FILES

from your request POST

.

0


source







All Articles