您好,登錄后才能下訂單哦!
本篇內容介紹了“Yii怎么使用Captcha驗證碼”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
本文實例講述了Yii使用Captcha驗證碼的方法。分享給大家供大家參考,具體如下:
1. Model:
將驗證碼加入UserLogin的一個屬性:
class UserLogin extends CFormModel { public $username; public $password; public $rememberMe; public $verifyCode; public function rules() { return array( // username and password are required array('username, password,verifyCode', 'required'), // rememberMe needs to be a boolean array('rememberMe', 'boolean'), // password needs to be authenticated array('password', 'authenticate'), // verifyCode needs to be entered correctly array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()), ); } /** * Declares attribute labels. */ public function attributeLabels() { return array( 'rememberMe'=>Yii::t('user',"Remember me next time"), 'username'=>Yii::t('user',"username or email"), 'password'=>Yii::t('user',"password"), 'verifyCode'=>Yii::t('user','Verification Code'), ); } }
2. Controller
在LoginController控制器加入映射動作CCaptchaAction
public function actions() { return array( // captcha action renders the CAPTCHA image displayed on the contact page 'captcha'=>array( 'class'=>'CCaptchaAction', 'backColor'=>0xf4f4f4, 'padding'=>0, 'height'=>30, 'maxLength'=>4, ), ); } ublic function actionLogin() { if (Yii::app()->user->isGuest) { $model=new UserLogin; // collect user input data if(isset($_POST['UserLogin'])) { $model->attributes=$_POST['UserLogin']; //在此核對驗證碼 if($this->createAction('captcha')->validate($model->verifyCode, false)) { // validate user input and redirect to previous page if valid if($model->validate()) { //admin login only if( Yii::app()->getModule('user')->isAdmin()==1 ) { $this->lastViset(); if (strpos(Yii::app()->user->returnUrl,'/index.php')!==false) $this->redirect(Yii::app()->controller->module->returnUrl); else $this->redirect(Yii::app()->user->returnUrl); }else {//if no admin when login out $this->redirect(Yii::app()->controller->module->logoutUrl); } } }else {//提示錯誤 $model->addError('verifyCode','驗證碼不對'); } } // display the login form $this->render('/user/login',array('model'=>$model)); } else $this->redirect(Yii::app()->controller->module->returnUrl); }
在驗證用戶名密碼前,檢查驗證碼:
if($this->createAction('captcha')->validate($model->verifyCode, false)) {
3. view
在視圖中顯示驗證碼圖片,輸入框
<?php $this->widget('CCaptcha'); ?> <?php echo CHtml::activeTextField($model,'verifyCode',array('tabindex'=>1)); ?> <img src="https://cache.yisu.com/upload/information/20201209/266/41208.jpg" alt="">
“Yii怎么使用Captcha驗證碼”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。