Yii框架captcha验证码的使用

来源:互联网 发布:iphone8支持5g网络吗 编辑:程序博客网 时间:2024/05/21 22:57
yii2框架自带验证码类,而且可以通过widget()方法直接渲染生成填写验证码的input框,以及验证码的图片.下面就记录如何使用验证码.

控制器

假设控制器为Auth,则在该控制器下重载actions,以下是基本的配置,更多的配置请查看官方文档 yii-captcha-captchaaction 章节

public function actions(){    return [        'captcha' => [            'class'     => 'yii\captcha\CaptchaAction',            'testLimit' => 2,//两次有效            'height'    => 40,            'width'     => 80,            'minLength' => 4,            'maxLength' => 4            ]        ];}

模型

假设验证码的字段为verifyCode,则在模型下的验证规则rules方法下,添加,注意captchaAction要配置正确,要和前端的配置对应.

public $verifyCode;public function rules(){ return [ ['verifyCode','captcha','captchaAction'=>'admin/auth/captcha','message'=>'验证码不正确'], ]; }

视图

有两种调用方式,个人比较喜欢第二种.
方式一

<?php $form=\yii\bootstrap\ActiveForm::begin();?><?= $form->field($model'verifyCode')->widget(\yii\captchat\Captcha::className,[    'captchaAction' =>'auth/captcha',//必须要和model中的一致    'template'      => '{input}{image}', //模板    'options'       => ['placeholder'=>'验证码'],//input框属性    'imageOptions'  => ['id'=>'captcha']    //图像的属性]);?><?php $form->end();?>

方式二

<?php $form=\yii\bootstrap\ActiveForm::begin();?><?= \yii\captcha\Captcha::widget([    'model'         => $model,    'attribute'     => 'verifyCode',    'captchaAction' => 'auth/captcha',    'options'       => ['placeholder'=>'验证码'],    'imageOptions'  => ['id'=>'captcha'],    'template'      => '{input}{image}',]);?><?php $form->end();?>

以上是基本的配置,更多的配置请查看 官方文档 yii-captcha-captcha 章节

刷新

$("#captcha").click(function(){var url = "<?= \yii\helpers\Url::to(['auth/captcha']);?>";$.get(url,{refresh:1},function(data){    var object = eval(data);    $('#captcha').attr('src',object.url);    })});
0 0
原创粉丝点击