如果在编辑PHP时文件上传为空,则防止空数据上载

时间:2018-04-27 03:26:11

标签: php

我有一个编辑页面,用户可以在其中更新他们的帖子信息(这是一个非wordpress网站)。该帖子只会显示最近更新的照片。如果他们没有上传任何新照片,则会上传一个空白文件。由于文件不存在,该空白文件将替换上传的带有损坏图像图标的最后一张照片。

普通照片在我的数据库中显示为images/filename.extension,其中包含id。如果未选择照片,则空数据将上传为images/,并且会将ID归于其中,即使其中没​​有任何内容存在。

如果在编辑提交期间没有选择文件,是否可以阻止发生此空文件上传?

如果有人有任何建议,我将不胜感激。

以下是仅与文件上传有关的部分:

for($i=0; $i<count($_FILES["images"]["name"]); $i++){
    $filetmp = $_FILES["images"]["tmp_name"][$i];
    $filename = $_FILES["images"]["name"][$i];
    $filetype = $_FILES["images"]["type"][$i];
    $filepath = "images/".$filename;
    move_uploaded_file($filetmp, $filepath);
    $sql = "INSERT INTO images (img_name, img_path, img_type, post_id)
            VALUES ('$filename', '$filepath', '$filetype', '$id')";
    $result = mysqli_query($db, $sql);
}

以下是提交的整个PHP编辑:

if(isset($_POST['submit'])){    
    $id = $_POST['id'];
    $title = $_POST['title'];
    $link = $_POST['link']; 
    $description = $_POST['description'];
    $start = date('Y-m-d', strtotime($_POST['start']));
    $end = date('Y-m-d', strtotime($_POST['end']));
    $title = $db->real_escape_string($title);
    $link = $db->real_escape_string($link);
    $description = $db->real_escape_string($description);
    $user_id = $_SESSION['user_id'];    
    if($title && $description){
        if ($update = $db->prepare("UPDATE post SET title='$title', link='$link', description='$description', start='$start', end='$end' WHERE post_id=$id")) {
            $update->execute();
            $update->fetch();
            $update->close();
        }    
        if($update){
            $_SESSION['message'] =  "The offer has been updated!";
        }else{
            $_SESSION['message'] =  "error";
        }
    }
    else{
        $_SESSION['message'] = "Please make sure required fields are filled out.";
    }  
    for($i=0; $i<count($_FILES["images"]["name"]); $i++){
        $filetmp = $_FILES["images"]["tmp_name"][$i];
        $filename = $_FILES["images"]["name"][$i];
        $filetype = $_FILES["images"]["type"][$i];
        $filepath = "images/".$filename;
        move_uploaded_file($filetmp, $filepath);
        $sql = "INSERT INTO images (img_name, img_path, img_type, post_id)
               VALUES ('$filename', '$filepath', '$filetype', '$id')";
        $result = mysqli_query($db, $sql);
    }
}

1 个答案:

答案 0 :(得分:1)

在检查文件大小的if语句中尝试使用文件上载和SQL代码。空文件应为0。

{{1}}

当然,您也可以检查其他参数,而不仅仅是尺寸。

相关问题