在php中使用mimetype检查文件扩展名之间的兼容性
如何确保文件具有指定的扩展名和mimetype,因为可能有人正在更改文件扩展名。这可用于防止上载具有相同文件扩展名但不同mimetype的文件 这是我的代码,但结果不是我想要的:在php中使用mimetype检查文件扩展名之间的兼容性,php,arrays,mime-types,file-extension,fileinfo,Php,Arrays,Mime Types,File Extension,Fileinfo,如何确保文件具有指定的扩展名和mimetype,因为可能有人正在更改文件扩展名。这可用于防止上载具有相同文件扩展名但不同mimetype的文件 这是我的代码,但结果不是我想要的: function mimeInfo($filename) { $realpath = realpath( $filename ); if ( $realpath && function_exists( 'finfo_file' ) && f
function mimeInfo($filename) {
$realpath = realpath( $filename );
if ( $realpath
&& function_exists( 'finfo_file' )
&& function_exists( 'finfo_open' )
&& defined( 'FILEINFO_MIME_TYPE' )
) {
// Use the Fileinfo PECL extension (PHP 5.3+)
return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
}
if ( function_exists( 'mime_content_type' ) ) {
// Deprecated in PHP 5.3
return mime_content_type( $realpath );
}
return false;
}
function uploadAllows($pathfile){
$fileAllows = array(
"rar"=>"application/x-rar",
"xls"=>array(
"application/vnd.ms-office",
"application/x-msexcel",
"application/x-excel",
"application/excel",
"application/vnd.ms-excel",
)
);
$mimeInfo = mimeInfo($pathfile);
$file = pathinfo($pathfile);
$ext = $file['extension'];
if(count($fileAllows[$ext])>1){
if(in_array($mimeInfo, $fileAllows[$ext])){
return true;
}else{
return false;
}
}else{
if(in_array($mimeInfo, $fileAllows)){
return true;
}else{
return false;
}
}
}
预期1:
1. extension must *.rar
2. mimetype must "application/x-rar"
预期2:
1. extension must *.xls
2. mimetype must one of the spesific array
谢谢。你应该这样做
// MIME types must be array even if there is only 1 of them
$fileAllows = array(
"rar"=>array("application/x-rar"),
"xls"=>array(
"application/vnd.ms-office",
"application/x-msexcel",
"application/x-excel",
"application/excel",
"application/vnd.ms-excel",
)
);
$mimeInfo = mimeInfo($pathfile);
$file = pathinfo($pathfile);
$ext = strtolower($file['extension']); // convert to lowercase
if(is_array($fileAllows[$ext])) return in_array($mimeInfo, $fileAllows[$ext]);
else return false;