Yii使用Captcha验证码的方法
本文实例讲述了Yii使用Captcha验证码的方法。分享给大家供大家参考,具体如下:
详细代码可参考:yii自带的示例代码post项目,里面有一个contact表单用到了验证码.
1.Model:
将验证码加入UserLogin的一个属性:
classUserLoginextendsCFormModel { public$username; public$password; public$rememberMe; public$verifyCode; publicfunctionrules() { returnarray( //usernameandpasswordarerequired array('username,password,verifyCode','required'), //rememberMeneedstobeaboolean array('rememberMe','boolean'), //passwordneedstobeauthenticated array('password','authenticate'), //verifyCodeneedstobeenteredcorrectly array('verifyCode','captcha','allowEmpty'=>!CCaptcha::checkRequirements()), ); } /** *Declaresattributelabels. */ publicfunctionattributeLabels() { returnarray( 'rememberMe'=>Yii::t('user',"Remembermenexttime"), 'username'=>Yii::t('user',"usernameoremail"), 'password'=>Yii::t('user',"password"), 'verifyCode'=>Yii::t('user','VerificationCode'), ); } }
2.Controller
在LoginController控制器加入映射动作CCaptchaAction
publicfunctionactions() { returnarray( //captchaactionrenderstheCAPTCHAimagedisplayedonthecontactpage 'captcha'=>array( 'class'=>'CCaptchaAction', 'backColor'=>0xf4f4f4, 'padding'=>0, 'height'=>30, 'maxLength'=>4, ), ); } ublicfunctionactionLogin() { if(Yii::app()->user->isGuest){ $model=newUserLogin; //collectuserinputdata if(isset($_POST['UserLogin'])) { $model->attributes=$_POST['UserLogin']; //在此核对验证码 if($this->createAction('captcha')->validate($model->verifyCode,false)) { //validateuserinputandredirecttopreviouspageifvalid if($model->validate()){ //adminloginonly 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 {//ifnoadminwhenloginout $this->redirect(Yii::app()->controller->module->logoutUrl); } } }else {//提示错误 $model->addError('verifyCode','验证码不对'); } } //displaytheloginform $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');?> <?phpechoCHtml::activeTextField($model,'verifyCode',array('tabindex'=>1));?> <imgsrc="http://www.XXXX.net/uploads/123456.jpg"alt="">
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。