2015-08-08 60 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