This article illustrates the method used by Yii to use CAPTCHA authentication codes. Share to everyone for your reference, specific as follows:
Detailed code can refer to: Yii from the sample Code post project, which has a contact table alone to the verification code.
1. Model:
Add a validation code to an attribute of 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 is authenticated
array (' Password ', ' Authenticate '),
//Verifycode needs to be entered Corre ctly
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
Add mapping actions to the Logincontroller controller ccaptchaaction
Public function actions () {return array (///CAPTCHA action renders the CAPTCHA image displayed on the contacts 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 '];//Check the verification code here if ($this->createaction (' Captcha ')->validate ($model->verifycode, False)) {//validate user input and Redi Rect to previous page if valid if ($model->validate ()) {//admin login only if (Yii::app ()->getmodule (' Us
Er ')->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 {//Hint error $model->adderror (' Verifycode ', ' Verify code is not correct ');
}//Display the login form $this->render ('/user/login ', Array (' model ' => $model));
else $this->redirect (Yii::app ()->controller->module->returnurl);
}
Check the authentication code before verifying the username password:
if ($this->createaction (' Captcha ')->validate ($model->verifycode, false))
{
3. View
Display the validation code picture in the view, enter the box
<?php $this->widget (' Ccaptcha ');?>
<?php Echo Chtml::activetextfield ($model, ' Verifycode ', Array (' TabIndex ' =>1);?>
I hope this article will help you with the PHP program design based on the YII framework.