如果没有文件上传,则停止file_exist调用错误

时间:2018-09-13 20:22:52

标签: php

当用户没有选择上传文件作为表单的一部分时,是否有一种简单的方法可以阻止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>";
}

1 个答案:

答案 0 :(得分:1)

由于您使用过elseif,因此我不确定您的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.');
}