上传文件防木马函数
项目环境:TP6、TP5
问题:解决旧项目中上传上来的文件校验不严格。导致会有木马文件入侵的情况发生。除了上篇博文中提及的限制上传文件存储的目录不可执行php文件外。仍需在入口处严格检验上传文件的类型,排除php类可执行文件上传。
解决:
/**
* 判断上传文件是否合法 如:php文件不可上传
*
* @author
* @param $file
* @return /bool
*/
function checkUploadFile($file, $only_php_check=true, $allowed_types=[], $allowed_extensions=[]) {
if (!isset($file)) {
return false;
}
$check_php = true;
//允许的文件类型(mimeType): application/vnd.ms-excel
//不允许的类型 text/x-php
$mime_type = strtolower($file->getMime());//text/x-php
$extension = strtolower($file->getOriginalExtension());//php
if($mime_type == 'text/x-php' || $extension == 'php'){
$check_php = false;//上传文件为php文件
}
if($only_php_check){//仅判断是否为php文件的话 此时就返回结果。终止后续判断了。
return $check_php;
}
// 允许的MIME类型数组和扩展名数组
if(!$allowed_types){
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'application/vnd.ms-excel'];
}
if(!$allowed_extensions){
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'xls'];
}
// 检查MIME类型和扩展名是否都在允许的列表中
if (in_array($mime_type, $allowed_types) && in_array($extension, $allowed_extensions)) {
return true;
} else {
return false;
}
}