如果要实现这个过程的话,需要几个步骤
第一步就是controller的操作
在要操作的控制器中添加如下代码:
public function actions(){return array( // captcha action renders the captcha image displayed on the contact page'captcha'=>array('class'=>'ccaptchaaction','backcolor'=>0xffffff, 'maxlength'=>'8', // 最多生成几个字符'minlength'=>'7', // 最少生成几个字符'height'=>'40','width'=>'230',), ); }public function accessrules(){return array(array('allow','actions'=>array('captcha'),'users'=>array('*'),),);}
第二步就是view的操作
在要显示验证码的地方添加如下代码:
widget('ccaptcha',array('showrefreshbutton'=>true,'clickableimage'=>false,'buttonlabel'=>'刷新验证码','imageoptions'=>array('alt'=>'点击换图','title'=>'点击换图','style'=>'cursor:pointer','padding'=>'10'))); ?>
第三步就是loginform的操作
'登录帐号不能为空'),array('password','required','message'=>'密码不能为空'),array('verifycode','required','message'=>'验证码不能为空'),array('verifycode','captcha', 'on'=>'login','allowempty'=>!yii::app()->admin->isguest),// rememberme needs to be a booleanarray('rememberme', 'boolean'),// password needs to be authenticatedarray('password', 'authenticate'),);}/*** declares attribute labels.*/public function attributelabels(){return array('rememberme'=>'下次记住我','verifycode' =>'验证码');}/*** authenticates the password.* this is the 'authenticate' validator as declared in rules().*/public function authenticate($attribute,$params){if(!$this->haserrors()){$this->_identity=new useridentity($this->username,$this->password);if(!$this->_identity->authenticate())$this->adderror('password','帐号或密码错误.');}}public function validateverifycode($verifycode){if(strtolower($this->verifycode) === strtolower($verifycode)){return true;}else{$this->adderror('verifycode','验证码错误.');}}/*** logs in the user using the given username and password in the model.* @return boolean whether login is successful*/public function login(){if($this->_identity===null){$this->_identity=new useridentity($this->username,$this->password);$this->_identity->authenticate();}if($this->_identity->errorcode===useridentity::error_none){$duration=$this->rememberme ? 3600*24*30 : 0; // 30 daysyii::app()->user->login($this->_identity,$duration);return true;}else{return false;} }}
第四步,实现验证的过程,那么具体的查看我自己的写的一个方式,在第三部已经写好了
validateverifycode就是啦,可以在controller里面调用
我的调用如下:
public function actionlogin(){$model=new loginform;if(isset($_post['ajax']) && $_post['ajax']==='login-form'){echo cactiveform::validate($model);yii::app()->end();}if(isset($_post['loginform'])){$model->attributes=$_post['loginform'];// validate user input and redirect to the previous page if validif($model->validate() && $model->validateverifycode($this->createaction('captcha')->getverifycode()) && $model->login()){$this->redirect(ccontroller::createurl('default/index'));}}$this->render('login',array('model'=>$model));}
以上就介绍了yii 验证码的使用和验证过程,包括了require,ajax方面的内容,希望对php教程有兴趣的朋友有所帮助。