php - PHP 无法识别文件上传扩展名
问题描述
在 php 中回显时,我有以下由 ajax 发送的数组
[file] => Array
( [name] => XXXX.jpg [type] => image/jpeg [tmp_name] => D:\xampp\tmp\phpC5F2.tmp
[error] => 0 [size] => 25245 )
以及处理上传的以下代码:
if(isset($_FILES['file'])) {
$natid = '9999';
$target_dir = "../uploads/";
$fname = $_FILES['file']['name'];
$target_file = $target_dir . $natid .'/'. $fname;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if($imageFileType == "jpg" && $imageFileType == "png" && $imageFileType == "jpeg" && $imageFileType == "gif") {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) { // !== not equal
echo "File is an image - " . $check["mime"] . ".<br>";
} else {
echo "the file is not an image.";
}
} elseif ($imageFileType == "pdf"){
echo "File is a PDF - " . $check["mime"] . ".<br>";
} else {
echo "Sorry, only PDF, JPG, JPEG, PNG & GIF files are allowed.";
}
}
当我运行代码时,我得到了 php 的回复,虽然该文件既不是图像也不是 PDF
$imageFileType 给了我'jpg'
解决方案
您混淆了&&
and||
运算符。
$imageFileType == "jpg" && $imageFileType == "png" && $imageFileType == "jpeg" && $imageFileType == "gif"
永远不可能是真的,因为 $imageFileType 永远不可能同时是这些值。而是让它像
$imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg" || $imageFileType == "gif"
或者,我个人觉得这个更漂亮:
$allowedTypes = array("jpg","png","jpeg","gif");
if (! in_array($imageFileType, $allowedTypes)){
//not allowed
}else{
//allowed
}
推荐阅读
- shell - 在 shell 中为 stderr 和 stdout 创建一个带有 tee 的管道
- git - 将 SVN 主干中的每个目录转换为不同的 GIT 存储库
- import - 将 Canva 设计导入 Webflow
- javascript - 如何在内容可编辑元素的根级别列表之后创建下一段?
- php - 每页都需要页脚和页眉,但错误 500
- javascript - 如何在 Visual Studio 中使用机密?
- node.js - 使用 graphql apollo 客户端发送 httpOnly cookie
- android - 为什么 Android 应用程序在一次启动时启动 3 次?
- python - Matplotlib 崩溃,退出代码为 -1073741819 (0xC0000005)
- flutter - Flutter:是否可以不按按钮自动切换屏幕?