PHP reports incorrect MIME type

允我心安 提交于 2020-01-06 18:07:49

问题


I am designing a simple PHP script to allow uploads of *.cpp source files. As a basic security measure, I check the MIME type of the temporary file before moving it to a permanent location. When I run file --mime myfile.cpp in Terminal (on Mac OS X) it shows up as text/x-c. Yet the server sees it as a application/octet-stream for some reason. In /etc/mime.types the "cpp" extension is there under text/x-c++src which leads me to believe it's an issue with MIME types on Mac.

I've tried the same procedure from Ubuntu and it works fine (it shows up as text/x-c++src). I am using Chrome on both computers.

It's not exactly a programming question per se, but there may be some PHP trick to this that I'm not familiar with.

$temp_file=$_FILES["file"]["type"];
if(($temp_file!="text/x-c++src")||($temp_file!="text/x-c")) {
    echo "<p style=\"color:red;font-style:italic\">Please upload a valid C++ file.</p>";
}

回答1:


The $_FILES['userfile']['type'] contains the mime-type which the browser sent (during the upload). You can use it, but you cannot trust it.

Try getting the mime-type from $_FILES['userfile']['tmp_name'] using:

$mime = mime_content_type($tmp_name);
// or, as this is deprecated:
$info = new finfo(FILEINFO_MIME_TYPE);
$mime = $info->file($tmp_name);

Or, you can guess by the original file-name's extension in strrchr($_FILES['userfile']['name'], '.').




回答2:


The server sees whatever type the browser that uploaded it says it is.

Browsers aren't very good at determining file types in general, and malicious uploaders can always override it.

You can't trust the mime type. If you want to reasonably reliably know what type of file it is, you have to use a utility like file to sniff the data.



来源:https://stackoverflow.com/questions/13389288/php-reports-incorrect-mime-type

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