【问题标题】:How do I check uploaded file is empty?如何检查上传的文件是否为空?
【发布时间】:2013-09-24 14:56:45
【问题描述】:

我正在尝试对上传的图像进行一些验证。当我检查是否已选择并上传任何图像时,如果没有上传图像,它应该返回错误消息。但在我的方法中它总是返回false

方法如下:

class event{

        private $dbh;
        private $post_data;


        public function __construct($post_data, PDO $dbh){
                $this->dbh = $dbh;
                $this->post_data = array_map('trim', $post_data);

        }

public function checkValidImages(){
            $errors = array();

            if(empty($this->post_data['event-images'])){
                $errors[] = 'Please select at least one image to upload.';
            }

            if(count($errors) > 0){
                return $errors;
            }else{
                return FALSE;
            }

        }

在这里调用它:

// Check all images are valid
        $images = new event($_FILES, $dbh);
        var_dump($imageErrors = $images->checkValidImages());

var_dump() 返回bool(false)

表格如下:

<form name="submit-event" action="submit-event.php" method="post" enctype="multipart/form-data">
<div class="large-12 columns no-padding">
<p>Select images for this event</p><br />
<input type="file" class="right" name="event-images[]" size="50" multiple="multiple" />
</div>
</form>

那么为什么即使我没有选择任何图像,我的方法也会返回 false。

【问题讨论】:

  • var_dump() 返回 bool(false) 表示没有错误。这就是您定义函数的方式。
  • 我刚刚意识到,如果我不选择要上传的图像并计算$_FILES['event-images']['name'] 它会返回1 而不是0。这很奇怪。当然,如果我没有选择任何东西,它应该返回零?

标签: php oop methods upload image-uploading


【解决方案1】:

当 HTML 文件输入为空时,浏览器仍会提交表单元素的名称,因此您仍会在 $_FILES 数组中获得该条目,但错误代码为 UPLOAD_ERR_NO_FILE,文件名为"".

无论如何,您都应该检查the error code,因为很多事情都可能出错。所以你的验证码变成这样:

$numOkayFiles = 0;
$numIntendedFiles = 0;
foreach ($_FILES['event-images']['error'] as $errorCode) {
    $numIntendedFiles += ($errorCode != UPLOAD_ERR_NO_FILE);
    switch ($errorCode) {
    case UPLOAD_ERR_OK:
        $numOkayFiles++;
        break;
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        $errors[] = 'Your file was bigger than the maximum allowed size.';
        break;
    case UPLOAD_ERR_NO_FILE:
        // ignore
        break;
    default:
        $errors[] = 'A problem occured during file upload.';
    }
}
if ($numIntendedFiles == 0) {
    $errors[] = 'Please select at least one image to upload.';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2023-02-16
    • 2021-12-25
    • 2013-03-31
    相关资源
    最近更新 更多