Yii框架集成Captcha验证码完整实现指南
本实例详细解析了如何在Yii框架中集成和使用Captcha验证码功能,旨在为开发者提供实用的参考方案。
具体的代码实现可参照Yii自带的post项目示例,其中contact表单模块已包含完整的验证码应用逻辑。
第一步是Model层的配置:
需要在UserLogin模型类中新增一个名为verifyCode的属性,用于接收用户输入的验证码内容。
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'),
);
}
}
第二步涉及Controller控制器的设置:
在LoginController中定义actions方法,并将captcha动作映射到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))
{
第三步是View视图层的处理:
在对应的视图文件中,需要渲染显示验证码的图片以及供用户输入的文本框。
<?php $this->widget('CCaptcha'); ?>
<?php echo CHtml::activeTextField($model,'verifyCode',array('tabindex'=>1)); ?>
希望上述关于Yii框架下PHP程序设计的内容能对大家有所帮助。