Image validator throws an error if it is not image file

I have a simple validator for image file input which looks like:

public function rules()
{
    return [
		['thumbnail', 'image', 'minWidth' => 800],
    ];
}

But as I try to send txt file it does not show error message but ImageValidator throws me an error: PHP Notice – yii\base\ErrorException
## getimagesize(): Read error!

protected function validateImage($image)
{
    if (false === ($imageInfo = getimagesize($image->tempName))) {
        return [$this->notImage, ['file' => $image->name]];
    }
    ...

Why this happened? Why it does not stop on image rule why it test getimagesize() if it is not image file?

After few times I have this workaround:

['thumbnail', 'image', 'minWidth' => 800, 'when' => function($model) {
    $check = @getimagesize($model->thumbnail->tempName);
    if( !$check ) $model->addError('thumbnail', 'File is not an image.');
    if( !$check['mime'] || !in_array($check['mime'], ['image/jpg', 'image/jpeg']) ) $model->addError('thumbnail', 'File is not jpeg.');
    return $check ? true : false;
}],

Hi @camohub,

image validator is an extension of file validator, and is intended to be used with the attributes of file validators also specified explicitly.

['thumbnail', 'image',
    'extensions' => ['png', 'jpg', 'gif'],
    'mimeTypes' => ['image/*'],
    'minWidth' => 800],

file validator and image validator

1 Like

@softark Yes it works. Thank you.