MIMEs, octet-stream and Uploadify

守給你的承諾、 提交于 2020-03-26 09:34:13

问题


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'], '.'), '.')


回答1:


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.



来源:https://stackoverflow.com/questions/6845866/mimes-octet-stream-and-uploadify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!