Today, when I upload and verify the mime value of an image, I suddenly find that the MIME value obtained by finfo_file cannot be directly used in some special cases,
According to the official statement
$ Finfo = finfo_open (FILEINFO_MIME );
$ Mime = finfo_file ($ finfo, $ file_path );
Finfo_close ($ finfo );
Alert ($ mime );
In this way, obtain the object mime type
But today we found that this is not the case. In file transmission, if charset sets the transmission type to binary stream, it will appear like this:
We can see that there is a semicolon and the character set = binary
If you verify the mime value of the file again, the verification fails even if the file type is correct and valid, because the obtained mime value is followed by a part of the binary file stream string "; charset = binary"
$ File_name = $ _ FILES ['imgfile'] ['name'];
$ Temp_arr = explode (".", $ file_name );
$ File_ext = array_pop ($ temp_arr );
$ File_ext = trim ($ file_ext );
$ File_ext = strtolower ($ file_ext );
$ _ Mime = array ('jpg '=> array ('image/pjpeg', 'image/jpeg '), 'gif' => array ('image/gif '), 'png '=> array ('image/x-png', 'image/png '), 'jpeg' => array ('image/jpeg ', 'image/pjpeg '));
If (empty ($ mime) |! In_array ($ mime, $ _ mime [$ file_ext]) {
Alert ('image mime type error! ');
}
Therefore, it is necessary to handle compatibility in special environments.
The general method for obtaining compatibility of mime types after modification is as follows (note the red part of some columns and obtain correct mime values in compatible environments with multiple requirements through regular expressions ):
If (empty ($ mime) & function_exists ('finfo _ open ')){
$ Finfo = finfo_open (FILEINFO_MIME );
$ Mime = finfo_file ($ finfo, $ file_path );
Finfo_close ($ finfo );
// Supports precise mime verification for file upload in special application environments
$ New = preg_match ('/([^;] + );?. * $/', $ Mime, $ match );
If ($ new) $ mime = trim ($ match [1]);
Alert ($ mime );
}
In this way, the mime types in the compatible environment can be correctly obtained and the file mime validity is verified. The running result is as follows: