yii验证码的使用

1.模型
模型中添加public $verifyCode;

<?php 
	namespace backend\models;
	
	use Yii;
	use yii\base\Model;
	use yii\db\ActiveRecord;
	class Adminuser extends ActiveRecord{
		public $username;
		public $password;
		public $verifyCode;
		public function rules(){
			return [
				['username','required','message'=>'用户名不能为空'],
				['password','required','message'=>'密码不能为空'],
				['verifyCode', 'captcha','message'=>'验证码输入错误'],
			];
		}
	}
?>

2.控制器
添加方法

public function actions()
	{
	  return [
	    'error' => [
	      'class' => 'yii\web\ErrorAction',
	    ],
	    //验证码
	    'captcha' => [
	      'class' => 'yii\captcha\CaptchaAction',
	      'backColor'=>0xffffff,//背景颜色
	      'maxLength' => 6, //最大显示个数
	      'minLength' => 5,//最少显示个数
	      'padding' => 5,//间距
	      'height'=>34,//高度
	      'width' => 120,  //宽度
	      'foreColor'=>0x000000,     //字体颜色
	      'offset'=>4,        //设置字符偏移量 有效果
	    ],
	  ];
	}

注意:可能你的验证码没有办法正常显示,这里可以删除控制器中的方法behaviors

3.视图

<?= $form->field($model, 'verifyCode')->widget('yii\captcha\Captcha', [
	'captchaAction'=>'site/captcha',
	'options' => [
		'placeholder' => '输入验证码',
	],
	'template' => '<div class="row"><div class="col-lg-6">{input}</div><div style="margin-left:40px;margin-top:10px;" class="col-lg-3">{image}</div></div>',
])?>

4.我们这里回遇到一个问题,当我们刷新网页的时候我们会发现,我们的验证码并不会刷新,解决方法
找到文件/vendor/yiisoft/yii2/captcha/CaptchaValidator.php

修改
$code = $captcha->getVerifyCode(false);

为:
$code = $captcha->getVerifyCode(true);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原克技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值