Reputation: 1562
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)
Upvotes: 3
Views: 9530
Reputation: 2428
$_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)
Upvotes: 1
Reputation: 44345
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.
Upvotes: 0
Reputation: 33447
The MIME element comes from the browser, which means it can be manipulated and thus is not trustworthy.
Either check the extension, or if you really want, parse the first few bytes of the file to make sure it's what is expected.
Upvotes: 3