Why does Laravel's getMimeType() method identify a file as “application/octet-stream” when the file has the type attribute of “audio/mpeg”?

旧街凉风 提交于 2019-12-03 01:55:54

The UploadedFile object is ultimately extended from Symfony\Component\HttpFoundation\File\UploadedFile which get/sets the mimeType from The type of the file as provided by PHP.

To access that mimeType you would need to call $file->getClientMimeType()

However in the Symfony docblock for the function it suggests:

The client mime type is extracted from the request from which the file was uploaded, so it should not be considered as a safe value.

For a trusted mime type, use getMimeType() instead (which guesses the mime type based on the file content).

In your case however $file->getMimeType() which should be trusted and guesses the mime type from the contents, however it returns something as if it cannot determine the mime type, being "application/octet-stream"

Additional information

To help you decide. Basically getClientMimeType() would return the mime type that was set by the browser.

The getMimeType call guesses the mime type using two different techniques that I can see:

  1. Using a binary mime type technique looking at the output of the following command file -b --mime %s 2>/dev/null if it is supported.

  2. The second technique is using the finfo_open command if it does exist inside php.

If both 1. and 2. exists on your system, from what I see 2. will take preference, and 1. will be the fallback.

I personally would favour the results from getMimeType() for security. However, it would be another interesting question to ask "How reliable is browser mime type detection, and what techniques are used" :-)

Updated example

I include an example for you.

For me doing a check on a "DropboxInstalled.dmg", here are my results:

  1. using file -b --mime DropboxInstaller.dmg from a commandline (terminal) returns application/octet-stream

  2. using finfo_open functionality

$finfo = new \finfo(FILEINFO_MIME_TYPE);
echo $finfo->file('./DropboxInstaller.dmg');

returns application/x-iso9660-image

I was having this issue with Laravel 5.4. I fixed by setting post_max_size and upload_max_filesize in my php.ini to a higher value.

After that, I actually had to do a hard restart of OSX before it would actually reflect in the application properly.

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