在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'
答案 0 :(得分:3)
您混淆了&&
和||
运算符。
$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
}