【问题标题】:input file empty handling输入文件空处理
【发布时间】:2014-09-30 14:02:28
【问题描述】:

所以,我有一个表单,它是文章表单,其中有标题、内容、图像(用于显示使用 javascript 从输入中选择的图像)和输入(用于选择图像),我使用

$upload_errors = array(
    // http://www.php.net/manual/en/features.file-upload.errors.php
    UPLOAD_ERR_OK               => "No errors.",
    UPLOAD_ERR_INI_SIZE     => "Larger than upload_max_filesize.",
  UPLOAD_ERR_FORM_SIZE  => "Larger than form MAX_FILE_SIZE.",
  UPLOAD_ERR_PARTIAL        => "Partial upload.",
  UPLOAD_ERR_NO_FILE        => "No file.",
  UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
  UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
  UPLOAD_ERR_EXTENSION  => "File upload stopped by extension."
);

检查我的输入文件是否有错误,是否可以正常添加新文章...

但是,如果我想编辑我的文章怎么办?通常我会重复使用相同的表单,但会回显选定的文章值并全部显示,它显示标题、内容、图像但不显示输入文件,我知道这是安全问题,所以例如我只想更改文章标题,我将收到错误“无文件”,因为我提交了包括输入文件在内的所有表单内容......那么这种问题有什么最佳实践吗?如果我没有选择任何图像,也许可以通过某种方式来识别它,然后我会通过它而不显示任何错误...

这是我处理错误的方法

$error = $_FILES['upload_file']['error'];
if ($error != 1) {
    $information->id = $_POST['id'];  
    $information->name = $_POST['name'];
    $name = $_POST['name'];
    $information->upload_image($_FILES['upload_file']['tmp_name']);

    $content = $_POST['content'];
    $entity_content = htmlentities($content);
    $entity_content = stripslashes(str_replace('\r\n', '',$entity_content));
    $information->content = $entity_content;
    try{
        if($information->save()){
            if(isset($_POST['simpan'])){
                redirect_to("show_information.php");
            }
        }else{
            $message = "failed to change information";
        }
    }catch(PDOException $e){
        $message = "failed to change information";
        error_notice($e);
    } 
}else{
    $message = $upload_errors[$error];
}

如果没有输入,我需要做什么来绕过错误检查?

【问题讨论】:

  • 你可以添加一个复选框,如果它被选中,你会运行一个不同的错误块,否则可能运行上面的那个?
  • 在你的测试中,检查文章是否已经存在;如果是这样,请忘记输入文件:if ($error != 1 or article_exists($_POST['id']) === true) 假设 article_exists() 如果文章存在则返回 true。在这种情况下不要upload_image()
  • 所以如果不在我的表单中添加复选框或其他内容就无法处理它?我只是在想一种让用户使用我的网络表单的最简单方法.... :(

标签: php html forms


【解决方案1】:

所以我只是得到了最好的解决方案....实际上很容易

$error = $_FILES['upload_file']['error']; 
if ($error == 0 || $error == 4) {
     if($error != 4)
     //do the uploading
}

在我的上传/保存类中,我只需要检查一下

if(!empty($image))
   // do move_uploaded_to 
   // do the saving with replacement of $image
else
   // do the saving without $image

$image 只是我将图像名称/路径放入 mysql 数据库的占位符

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多