YII2框架中验证码的简单使用方法示例
本文实例讲述了YII2框架中验证码的简单使用方法。分享给大家供大家参考,具体如下:
验证码的使用是比较频繁的。YII2中已经帮我们做好了封装。
首先我们在控制器里创建一个actions方法,用于使用yii\captcha\CaptchaAction
request->isPost){
//获取post过来的验证码
$verify=YII::$app->request->post('verify');
//我们手动进行验证,第二个参数表示是否区分大小写
if($this->createAction('captcha')->validate($verify,false)){
echo'成功';
}else{
echo'失败';
}
}else{
return$this->renderPartial('index');
}
}
//actions的作用主要是共用功能相同的方法
//当用户访问index/captcha时,actions就会调用yii\captcha\CaptchaAction方法
publicfunctionactions()
{
return[
'captcha'=>[
'class'=>'yii\captcha\CaptchaAction',
'fixedVerifyCode'=>null,
//背景颜色
'backColor'=>0x000000,
//最大显示个数
'maxLength'=>4,
//最少显示个数
'minLength'=>4,
//间距
'padding'=>2,
//高度
'height'=>30,
//宽度
'width'=>85,
//字体颜色
'foreColor'=>0xffffff,
//设置字符偏移量
'offset'=>4,
],
];
}
}
显示页面代码如下:
分页显示 "method="post"> 验证码:
">
request->csrfToken;?>"> $(function(){ //处理点击刷新验证码 $("#verifyImg").on("click",function(){ $.get("?refresh",function(data){ $("#verifyImg").attr("src",data["url"]); },"json"); }); });