从PHP中的数组检查上传的文件类型。
-
18-09-2019 - |
题
如何可以检查文件扩展名和mime类型是在阵列中,这是我现在有代码。
$upload_project_thum = $_FILES['upload_project_thum']['name'];
$upload_project_thum_ext = substr($upload_project_thum, strrpos($upload_project_thum, '.') + 1);
$upload_permitted_types= array('image/jpeg:jpg','image/pjpeg:jpg','image/gif:gif','image/png:png');
然后,向下其中i正在检查,如果该文件是一个有效的I型有此foreach循环
foreach ($upload_permitted_types as $image_type) {
$type = explode(":", $image_type);
if (($type[0] != $_FILES['upload_project_thum']['type']) && ($upload_project_thum_ext != $type[1]) ) {
$errmsg_arr[] = 'Please select a jpg, jpeg, gif, or png image to use as the project thumbnail'. $type[1] . " Type: ". $type[0];
$errflag = true;
}
的问题是,如果文件类型不是阵列中所有的类型(这是不可能的)我得到一个错误。它的工作原理到如果上传文件是数组中的错误信息不会触发点。
解决方案 3
我现在这样做的方式是:
$upload_permitted_types['mime']= array('image/jpeg','image/gif','image/png');
$upload_permitted_types['ext']= array('jpeg','jpg','gif','png');
if(!in_array($_FILES['upload_project_thum']['type'],$upload_permitted_types['mime']) || !in_array($upload_project_thum_ext,$upload_permitted_types['ext'])
{
$errmsg_arr[] = 'Please select a jpg, jpeg, gif, or png image to use as the project thumbnail';
$errflag = true;
}
到这样做的好处是,它会允许与JPEG的一个MIME .gif文件。所以它不强制矿山和扩展匹配但并确保它们都是图像类型。
其他提示
if (!in_array($_FILES['upload_project_thum']['type'], $upload_permitted_types)){
exit("Unsupported file type");
}
if( !in_array( $_FILES['upload_project_thum']['type'] . ':' . $upload_project_thum_ext, $upload_permitted_types) ) {
Trigger-error-here;
}
此应该寻找从两者的类型和扩展胶合适当的字符串。
另一种方法是修改您的循环那样:
$is_allowed = false;
foreach ($upload_permitted_types as $image_type) {
$type = explode(":", $image_type);
if (($type[0] == $_FILES['upload_project_thum']['type']) && ($type[1] == $upload_project_thum_ext ) ) {
$is_allowed = true;
break;
}
}
if( !$is_allowed ) {
$errmsg_arr[] = 'Please select a jpg, jpeg, gif, or png image to use as the project thumbnail'. $type[1] . " Type: ". $type[0];
$errflag = true;
}
我喜欢得到文件数组,然后使用foreach循环literating在可能的条件
$is_error = TRUE;
$allowFileTypes = array(
"image/png","image/jpg","image/jpeg"
);
$UserBaseFolder = 'userfiles/'.$_SESSION['user_id'];
if(!file_exists($UserBaseFolder)) {
mkdir("userfiles/".$_SESSION['user_id']."/");
}
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
foreach($_FILES as $dat => $f) {
if($f['size'] == "0") {
$msg .= '<p><span class="alert alert-danger">You must upload a file.</span></p>';
$is_error = FALSE;
}
if($f['size'] > "2000000") {
$msg .= '<p><span class="alert alert-danger">Your file size is too big.</span></p>';
$is_error = FALSE;
}
if(!in_array($f['type'],$allowFileTypes)){
$msg .= '<p><span class="alert alert-danger">Your file has invalid format. Please try again...</span></p>';
$is_error = FALSE;
} else {
$filepath = $UserBaseFolder.'/'.time().'-'.$f['name'];
move_uploaded_file($f["tmp_name"], $filepath);
}
返回$ MSG;
不隶属于 StackOverflow