我給的圖像文件類型的驗證規則是:圖像擴展驗證錯誤
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