首先在控制器裏面添加這一段(我的註冊方法是寫在user控制器裏面):
- public function actions()
- {
- return array(
- // captcha action renders the CAPTCHA image displayed on the contact page
- 'captcha'=>array(
- 'class'=>'CCaptchaAction',
- 'backColor'=>0xCCCCCC,
- 'maxLength'=>4, // 最多生成幾個字符
- 'minLength'=>4, // 最少生成幾個字符
- //'testLimit'=>1,
- ),
- );
- }
我這邊註冊要用到的是Member模型,需要在模型裏面添加:
- public $authcode;
- //...
- /**
- * @return array validation rules for model attributes.
- */
- public function rules()
- {
- // NOTE: you should only define rules for those attributes that
- // will receive user inputs.
- return array(
- //...
- array('authcode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'reg'),//驗證碼
- //...
- );
- }
然後在註冊頁面(我的路徑是views/user/reg.php)添加驗證碼:
- <?php $this->widget('CCaptcha',array('showRefreshButton'=>false,'clickableImage'=>true,'imageOptions'=>array('alt'=>'點擊換圖','title'=>'點擊換圖','style'=>'cursor:pointer'))); ?>
添加好了以後,頁面上就能顯示驗證碼了,然後就是在控制器的 reg 方法裏面去驗證用戶輸入的是否正確:
- $authcode = $this->getParam('authcode');//獲取參數
- $model = new Member('reg');//設定場景
- $model->authcode = $authcode;//將用戶填寫的驗證碼放到 model 裏面
- $model->validate();//在 save() 之前先驗證一下就行了
還有一種手動獲取驗證碼並驗證的方法,直接獲取 session 裏面的驗證碼和接收到的參數進行比較:
- //驗證碼
- if($this->createAction('captcha')->getVerifyCode() != $this->getParam('authcode')){
- //提示信息
- //...
- exit;
- }