当用户没有选择上传文件作为表单的一部分时,是否有一种简单的方法可以阻止file_exists返回true?
我有以下代码;
if (isset($_FILES["tipimage"]) && $_FILES["tipimage"]["error"] == 0) {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["tipimage"]["name"];
$filetype = $_FILES["tipimage"]["type"];
$targetDir = "uploads/";
$targetFilePath = $targetDir . $filename;
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) {
$error .= "Invalid File Format<br>";
}
}
if (file_exists("uploads/" . $_FILES["tipimage"]["name"])) {
$error .= "The File " . $_FILES["tipimage"]["name"] . " already exists.<br>";
} else if (move_uploaded_file($_FILES["tipimage"]["tmp_name"], $targetFilePath)) {
$successmsg .= "<div class='alert alert-success'>Image - " . $filename . " - Uploaded Successfully!</div>";
}
答案 0 :(得分:1)
由于您使用过else
和if
,因此我不确定您的else if
状况。如果可能,我会尽量避免错误。
// Check if the file exists
if(file_exists("uploads/" . $_FILES["tipimage"]["name"])){
$error .= "The File " . $_FILES["tipimage"]["name"] . " already exists.<br>";
}
// Upload file
if(!move_uploaded_file($_FILES["tipimage"]["tmp_name"], 'uploads/' . $_FILES["file_upload"]["name"])){
die('Error uploading file - check destination is writeable.');
}
$successmsg .= "<div class='alert alert-success'>Image - " . $filename . " - Uploaded Successfully!</div>";
// Check for errors
if($_FILES["file_upload"]["error"] > 0){
die('An error ocurred when uploading.');
}