本文实例讲述了yii使用captcha验证码的方法。分享给大家供大家参考,具体如下:
详细代码可参考:yii自带的示例代码post项目,里面有一个contact表单用到了验证码.
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="http://www.xxxx.net/uploads/123456.jpg" alt="">
希望本文所述对大家基于yii框架的php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!