简体   繁体   中英

PHP reports incorrect MIME type

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/xc . 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>";
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM