2015-08-08 42 views
1

我给的图像文件类型的验证规则是:图像扩展验证错误

array('employeedetails_photo', 'file', 'types' => 'jpg,gif,png', 'allowEmpty' => true,'on' => 'insert', 'on' => 'update'), 

但是,问题是,如果.doc文件的扩展名更改为.docx.jpg并上传这是员工的照片也被接受。如何在yii中验证这个问题?

+0

试试这个http://www.bitrepository.com/how-to-validate-an-image-upload.html – vietnguyen09

回答

1

验证图片的最好方法是使用GD imagecreatefrom*(或Imagick)重新创建图片并保存/替换处理后的图片。最简单的例子

public function rules(){ 
    return array(
    array('employeedetails_photo', 'validateImage') 
); 
} 

public function validateImage($attribute){ 
    $file = CUploadedFile::getInstance($this, $attribute); 
    if (!$file) { 
    return; 
    } 
    // http://php.net/manual/en/function.imagecreatefromstring.php 
    // These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2 
    $gd = @imagecreatefromstring(file_get_contents($file->getTempName())); 
    if ($gd === false) { 
    $this->addError($attribute, 'Image is corrupted'); 
    } 
} 
+0

工程....太感谢你了.... ..................... – Arya

+0

这是一个图像的权利。如果像这样验证doc文件,会做什么? – Arya

+0

使用本机CFileValidator并检查扩展和MIME类型。 'array('employeedetails_photo','file','mimeTypes'=> [],'types'=> [])'@Arya – SiZE