我给的图像文件类型的验证规则是:图像扩展验证错误
array('employeedetails_photo', 'file', 'types' => 'jpg,gif,png', 'allowEmpty' => true,'on' => 'insert', 'on' => 'update'),
但是,问题是,如果.doc
文件的扩展名更改为.docx.jpg
并上传这是员工的照片也被接受。如何在yii中验证这个问题?
我给的图像文件类型的验证规则是:图像扩展验证错误
array('employeedetails_photo', 'file', 'types' => 'jpg,gif,png', 'allowEmpty' => true,'on' => 'insert', 'on' => 'update'),
但是,问题是,如果.doc
文件的扩展名更改为.docx.jpg
并上传这是员工的照片也被接受。如何在yii中验证这个问题?
验证图片的最好方法是使用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');
}
}
您必须使用文件mimetype检查文件类型。 Php应该为你做。 use mime-content-type function
试试这个http://www.bitrepository.com/how-to-validate-an-image-upload.html – vietnguyen09