php - 在 php 中使用 mimetype 检查文件扩展名之间的兼容性
问题描述
如何确保文件具有指定的扩展名和 mimetype,因为它可能是有人更改文件扩展名。这可用于防止具有相同文件扩展名但不同 mimetype 的文件上传。
这是我的代码,但结果不是我想要的:
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;
推荐阅读
- javascript - 有没有办法在 Google Docs 的文本编辑器中以编程方式插入文本框或绘图?
- python - 在 Pandas 中添加唯一列和过滤器
- sql - 按日期求和,两张表
- oauth-2.0 - 从 Linkedin V2 API 获取 SocialActions - 权限错误
- google-chrome - 将 Google 查询字符串格式化为日期
- c# - 拆分字符串并知道结果的相对位置
- javascript - mxGraph 中的自动滚动溢出文本
- mysql - SSMS 中的 SSIS 包 - ADO NET 源无法获取连接 - 无法创建托管连接管理器
- c# - 无法将类型“字符串”隐式转换为“Microsoft.Azure.Management.DataFactory.Models.SecretBase”
- ionic-framework - 白色闪屏