我的页面上有一个图片上传部分。用户只能上传图片格式。我已经创建了使用PATHINFO_EXTENSION检查文件扩展名的代码。
if(isset($_POST['addstaff']))
{
$name=$_POST['name'];
$photo=$_FILES['photo']['name'];
$phototmp=$_FILES['photo']['tmp_name'];
$location="staff/";
$uploading=move_uploaded_file($phototmp,"staff/".$photo);
$up="staff/".$photo;
$imageFileType = strtolower(pathinfo($photo,PATHINFO_EXTENSION));
$empid=$_POST['empid'];
$pass=$_POST['pass'];
$password=password_hash($pass,PASSWORD_BCRYPT);
$branch=$_POST['branch'];
$doj=$_POST['doj'];
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "<script>alert('Sorry, only JPG, JPEG, PNG & GIF files are allowed.');</script>";
}
else{
$query="insert into staffdetails value('','$name','$empid','$branch','$doj','$up')";
$exe=mysqli_query($con,$query);
if($exe){
echo "<script>alert('Inserted');</script>";
}
else{
echo "errr".mysqli_error($con);
}
}
}
这里的问题是,当我上传一个php文件或其他文件而不是图像文件时,它正确显示了警告消息“对不起,只允许JPG,JPEG,PNG和GIF文件。”但它也会插入文件。我在if else
条件中添加了此条件,然后if和else条件如何一起工作。请任何人帮助
答案 0 :(得分:1)
验证成功后,您应该调用move_uploaded_file()函数
将代码更改为以下
if(isset($_POST['addstaff']))
{
$name=$_POST['name'];
$photo=$_FILES['photo']['name'];
$phototmp=$_FILES['photo']['tmp_name'];
$location="staff/";
$up="staff/".$photo;
$imageFileType = strtolower(pathinfo($photo,PATHINFO_EXTENSION));
$empid=$_POST['empid'];
$pass=$_POST['pass'];
$password=password_hash($pass,PASSWORD_BCRYPT);
$branch=$_POST['branch'];
$doj=$_POST['doj'];
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "<script>alert('Sorry, only JPG, JPEG, PNG & GIF files are allowed.');</script>";
}
else{
$uploading=move_uploaded_file($phototmp,"staff/".$photo);
$query="insert into staffdetails value('','$name','$empid','$branch','$doj','$up')";
$exe=mysqli_query($con,$query);
if($exe){
echo "<script>alert('Inserted');</script>";
}
else{
echo "errr".mysqli_error($con);
}
}
}