我遇到了一个棘手的情况。
我有一个图片上传字段,并且根据是否有任何错误(不正确的文件类型,文件大小太大,重复上传),它会抛出错误而不让他们上传它并显示通知他们的引导警报。
但是,此警报会在页面刷新时保留,或者即使他们导航到网站的其他页面并返回,警报也会恢复。
我已经尝试将错误变量导出到javascript并在一段时间后将其清空,或者当用户点击X关闭警报但没有一个工作时,警报仍会在返回时返回到页面。
我不认为cookie会有所帮助,因为图片上传后页面会刷新以显示图片,所以如果我设置了cookie然后页面刷新浏览器就会看到cookie被设置并删除数组然后用户可以甚至看到它。
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$message[] = "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
$message[] = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$message[] = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
$message[] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$uImageLink = "images/" . basename( $_FILES["fileToUpload"]["name"]);
try
{
$DB_host = "localhost";
$DB_user = "none of";
$DB_pass = "your";
$DB_name = "business";
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt = $DB_con->prepare("UPDATE `users` SET `Image` = :uImage WHERE `Id` = :uId");
$stmt->bindparam("uId", $uId);
$stmt->bindparam("uImage", $uImageLink);
$stmt->execute();
$user->redirect('http://mysite/yo');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
} else {
$message[] = "Sorry, there was an error uploading your file.";
}
}
然后在我的HTML下面:
<?php
for ($i = 0; $i < count($message); $i++) {
echo '
<div class="alert alert-danger">'. $message[$i] . '</div>
';
}
?>
答案 0 :(得分:1)
除非实际上传了这些代码,否则不应该调用所有这些代码。
假设用户尚未上传图片,请查看代码中的选定语句:
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
// you should've seen an undefined index error in your logs, and $target_file now equals "images/"
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// "images/" doesn't have an extension so this is empty
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
// an empty string isn't going to match any of those
$message[] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// oh look, $message is populated now!
for ($i = 0; $i < count($message); $i++) {
echo '
<div class="alert alert-danger">'. $message[$i] . '</div>
';
}