yii 中的驗證碼

首先在控制器裏面添加這一段(我的註冊方法是寫在user控制器裏面):

  1. public function actions() 
  2.     return array
  3.         // captcha action renders the CAPTCHA image displayed on the contact page   
  4.         'captcha'=>array
  5.             'class'=>'CCaptchaAction'
  6.             'backColor'=>0xCCCCCC, 
  7.             'maxLength'=>4,   // 最多生成幾個字符   
  8.             'minLength'=>4,   // 最少生成幾個字符 
  9.             //'testLimit'=>1, 
  10.         ), 
  11.     ); 

我這邊註冊要用到的是Member模型,需要在模型裏面添加:

  1. public $authcode
  2. //... 
  3. /**  
  4.  * @return array validation rules for model attributes.  
  5.  */  
  6. public function rules()  
  7. {  
  8.     // NOTE: you should only define rules for those attributes that  
  9.     // will receive user inputs.  
  10.     return array
  11.         //... 
  12.         array('authcode''captcha''allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'reg'),//驗證碼  
  13.         //...  
  14.     );  
  15. }  

然後在註冊頁面(我的路徑是views/user/reg.php)添加驗證碼:

  1. <?php $this->widget('CCaptcha',array('showRefreshButton'=>false,'clickableImage'=>true,'imageOptions'=>array('alt'=>'點擊換圖','title'=>'點擊換圖','style'=>'cursor:pointer'))); ?> 

添加好了以後,頁面上就能顯示驗證碼了,然後就是在控制器的 reg 方法裏面去驗證用戶輸入的是否正確:

  1. $authcode $this->getParam('authcode');//獲取參數 
  2. $model = new Member('reg');//設定場景 
  3. $model->authcode = $authcode;//將用戶填寫的驗證碼放到 model 裏面 
  4. $model->validate();//在 save() 之前先驗證一下就行了 

還有一種手動獲取驗證碼並驗證的方法,直接獲取 session 裏面的驗證碼和接收到的參數進行比較:

  1. //驗證碼  
  2. if($this->createAction('captcha')->getVerifyCode() != $this->getParam('authcode')){  
  3.     //提示信息 
  4.     //... 
  5.     exit;  
  6. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章