如何检查上传的文件是否为空?

时间:2013-09-24 14:56:46

标签: php oop methods upload image-uploading

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

1 个答案:

答案 0 :(得分:0)

当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.';
}