I'm using Uploadify and Kohana and I'm creating file uploader. User can upload only few types of files.
Kohana have great library of MIME types built-in. I thought that it would be cool to check that MIME type of uploaded file (it came from Uploadify) match setted file extensions. That's why I made an array of allowed MIME types.
$mimes = (array) Kohana::config('mimes');
$allowed_mimes = array_merge($mimes['bmp'], $mimes['gif'], $mimes['jpg'], $mimes['jpeg'], $mimes['png']);
Next, I wanted to check that uploaded files MIME type is in $allowed_mimes
array. I used something like in_array($file['type'], $allowed_mimes)
. For surprise to me - actual MIME of file was application/octet-stream
. Anyway, uploaded file was JPEG
image. How this is possible?
Basic idea is that I need to check file type. What's the best way to do it?
Edit:
After some conversions with my colleagues, I decided to check chars after last dot. Like virus.jpeg
is acceptable, because of jpeg
is in its name. i'm still open for better solutions!
$extension = ltrim(strrchr($file['name'], '.'), '.')
PHP can use fileinfo and MIME Magic (has been removed from PHP 5.3.0) to determine files' MIME type (and so does Kohanas' File::mime()
method).
In case that none of these 2 is available, this method will try to find the MIME type using files' extension, which can be highly unreliable.
Since you are only trying to validate some upload, I'd suggest using Upload
methods to validate it:
$validation = Validation::factory($_FILES)
->rule('Filedata', 'Upload::not_empty')
->rule('Filedata', 'Upload::valid')
->rule('Filedata', 'Upload::size', array(':value', '4M'))
->rule('Filedata', 'Upload::type', array(':value', array('bmp','jpg','jpeg','png')))
->rule('Filedata', 'Upload::image', array(':value', 1920, 1080));
Notice that Upload::image()
is available since 3.2.0 (you can import it into older versions as well). This is the validation I'm personally using for some Uploadify upload, so it should work just fine.