0

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

4

1 回答 1

0

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

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

$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.';
}
于 2013-09-24T17:25:09.537 回答