控制器LoginController.php

<?php
namespace backend\controllers;
use Yii;
use yii\debug\models\search\Log;
use yii\web\Controller;
use backend\models\Login;
use frontend\models\ContactForm;
use Illuminate\Http\Request;
use yii\web\Session;
use backend\controllers\CommonController; class LoginController extends Controller
{
public function actions(){
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength'=>4,
'minLength'=>4,
],
];
}
public function actionIndex(){
//调用model
$model = new Login();
if ($model->load(Yii::$app->request->post()) && $model->validate()){
return $this->refresh();
}
//我的view里面是login,所以下面是login
 return $this->render('login',[
'model'=>$model,
]);
}

}

model里面Login.php

<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\db\Query;
use common\models\User; class Login extends Model
{
public $verifyCode;
public $username;
public $password;
private $_user;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// [['username'], 'required','message'=>'用户名不能为空'],
[[ 'password'], 'required','message'=>'密码不能为空'],
// verifyCode needs to be entered correctly
['verifyCode', 'required','message'=>'验证码不能为空'],
['verifyCode', 'captcha','message'=>'验证码不正确'],
['username', 'unique', 'targetClass' => '\frontend\models\Login', 'message' => '用户名已存在.'],
];
}
/**
* @return array customized attribute labels
*/
public function attributeLabels()
{
return [
'rememberMe'=>'下次记住我',
'verifyCode' =>''
];
} /**
* @param $verifyCode
* @return bool
*/
public function validateVerifyCode($verifyCode){
if(strtolower($this->verifyCode) === strtolower($verifyCode)){
return true;
}else{
$this->addError('verifyCode','验证码错误.');
}
} /**
* @param $username
* @param $password
* @return int|string
* 验证用户名,密码返回C层
*/
public function code($username,$password){
$sql="select * from admin where admin_name='$username'";
$db =\Yii::$app->db->createCommand($sql)->queryOne();
if($db){
if($db['admin_pwd']==md5($password)){
return 0;
}else{
return "-1";
}
}else{
return "1";
}
}
} view里面login
<?php
use common\widgets;
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
use yii\helpers\Url;
use yii\widgets\LinkPager;
use yii\base;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/login.css" />
</head>
<body> <div class="page">
<div class="loginwarrp">
<div class="logo">管理员登陆</div>
<div class="login_form"> <?php $form=ActiveForm::begin([
'action'=>Url::toRoute(['show']),
'method'=>'post',
]); ?>
<th>姓名:</th><input type="text" name="username" style="width: 206px;height: 32px"><br><br>
<th>密码:</th><input type="password" name="password" style="width: 206px;height: 32px"><br><br>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-4">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?> <div class="form-group">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?= Html::submitButton('登录一下', ['class' => 'btn btn-primary']) ?>
</div> <?php ActiveForm::end(); ?>
</div>
</div>
</div>
</body>
</html>
在下面还需要改yii2里面原生代码,想知道这是为什么吗???因为原生代码是site/captcha,应该是两个php页面有
vendor/yiisoft/yii2/captcha/Captcha.php
还有一个我给忘记了 就在这个文件里captcha

网上的大多数解决方法都是通过修改vendor/yiisoft/yii2/captcha/CaptchaAction.php中的代码来解决,以下两种方法可以任选其一:

1.修改getVerifyCode()方法的参数默认值

将参数$regenerate的默认值由false改为true,这样在不传参数的情况下,程序每次获取验证码时都会重新生成。

2.修改run()方法

在红色箭头指向的地方中,添加一个参数true,同样可以解决问题。


带来的问题

使用上面两种方法确实都可以解决验证码不刷新的问题,但这样会带来一个新的问题,就是在开启表单客户端验证(enableClientValidation)的情况下,即使用户输入了正确的验证码,网页仍然会提示“验证码错误”:

那肿么办呢?在这里我们可以选择关闭表单的客户端验证功能,以此来解决这个问题:

但这种解决方法不是很完美,因为关闭了客户端的验证功能后,表单数据就只能提交到后台后再验证了,这样无疑会增加服务器的压力。


完美解决方法

上面说了那么多,解决方法貌似都不是很完美,其实要完美解决验证码不刷新的问题十分简单,我们不需要修改CaptchaAction.php,只要修改vendor/yiisoft/yii2/captcha/CaptchaValidator.php这个文件就可以了,修改的地方见下图

在红色箭头指向的地方,将参数false改为true即可完美解决问题。


总结

归根到底,是因为yii2在渲染Captcha小部件的时候,会先输出js验证代码,然后再渲染验证码图片,也就是说,验证码字符串必须在输出js代码前就要重新生成,而CaptchaAction.php中的run()方法是渲染验证码图片的时候调用的,CaptchaValidator.php中的clientValidateAttribute()是输出js代码的时候调用的,所以接下来的道理,相信大家都已经明白了。

yii2图片验证码的更多相关文章

  1. 字符型图片验证码识别完整过程及Python实现

    字符型图片验证码识别完整过程及Python实现 1   摘要 验证码是目前互联网上非常常见也是非常重要的一个事物,充当着很多系统的 防火墙 功能,但是随时OCR技术的发展,验证码暴露出来的安全问题也越 ...

  2. android图片验证码--自绘控件

    自绘控件的内容都是自己绘制出来的 大致流程如下: 1.定义一个类继承view 使用TypedArray初始化属性集合 在view的构造方法中 有一个AttributeSet的参数 很明显是用来保存控件 ...

  3. webform(十)——图片水印和图片验证码

    两者都需要引入命名空间:using System.Drawing; 一.图片水印 前台Photoshuiyin.aspx代码: <div> <asp:FileUpload ID=&q ...

  4. Android-简单的图片验证码

    Android-图片验证码生成1.为啥要验证码?图片验证码在网络中使用的是比较普遍的.一般都是用来防止恶意破解密码.刷票.论坛灌水.刷页等.2.怎样的验证码比较好?验证码的获取方式无非就两种,一种是后 ...

  5. 在mvc中实现图片验证码的刷新

    首先,在项目模型(Model)层中建立一个生成图片验证码的类ValidationCodeHelper,代码如下: public class ValidationCodeHelper { //用户存取验 ...

  6. Webform 文件上传、 C#加图片水印 、 图片验证码

    文件上传:要使用控件 - FileUpload 1.如何判断是否选中文件? FileUpload.FileName - 选中文件的文件名,如果长度不大于0,那么说明没选中任何文件 js - f.val ...

  7. php 图片验证码生成 前后台验证

    自己从前一段时间做了个php小项目,关于生成图片验证码生成和后台的验证,把自己用到的东西总结一下,希望大家在用到相关问题的时候可以有一定的参考性. 首先,php验证码生成. 代码如下: 1.生成图像代 ...

  8. python 识别图片验证码报IOError

    说一下困扰了我一周的问题:识别图片验证码 本来我按照安装步骤(http://www.cnblogs.com/yeayee/p/4955506.html?utm_source=tuicool&u ...

  9. Atitit 图片 验证码生成attilax总结

    Atitit 图片 验证码生成attilax总结 1.1. 图片验证码总结1 1.2. 镂空文字  打散 干扰线 文字扭曲 粘连2 1.1. 图片验证码总结 因此,CAPTCHA在图片验证码这一应用点 ...

随机推荐

  1. checkbox批量操作

    hang=data.split("\1");//获取 查询返回的数据 处理数据 var str=""; for(var i =0;i<hang.lengt ...

  2. 兼容不同浏览器的 CSS Hack 写法

    所谓 CSS Hack,是指在 CSS 代码中嵌入诸如 *,*html  等代码,方便于独立控制某种浏览器的具体样式.比如有些 CSS Hack 只能被 IE6 或 IE7 识别,而 Firefox ...

  3. edgerouter bonding

    configure set interfaces bonding bond0 mode 802.3ad set interfaces ethernet eth1 bond-group bond0 se ...

  4. [帖子收集]通用Windows平台(UWP)

    通用Windows平台,universal windows platform,UWP 什么是通用 Windows 平台 (UWP) 应用?(微软MSDN) 如何在通用 Windows 平台应用中使用现 ...

  5. LeetCode 395. Longest Substring with At Least K Repeating Characters C#

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  6. 用sql实现汉字转拼音

    有时我们会需要将汉字转为拼音,例如需要将省市转为拼音后当做编码存储(尽管国家有统一的标识码,但有时候我们还是会用到),网络上也有工具提供汉字转拼音的功能,但各有优劣,一般转拼音后还会存在带声调的字母, ...

  7. Debian7安装php5.5/5.6

    ### 1 添加源 echo "deb http://packages.dotdeb.org wheezy-php56 all" >> /etc/apt/sources ...

  8. js构造函数的完美继承(欢迎吐槽)

    function Animal(){ //定义父类 this.leibie="动物"; } Animal.prototype.test1=[1,2]; function Cat(n ...

  9. JMM内存管理

    原文地址http://www.cnblogs.com/BangQ/p/4045954.html 原本准备把内存模型单独放到某一篇文章的某个章节里面讲解,后来查阅了国外很多文档才发现其实JVM内存模型的 ...

  10. php系统无法上传图片问题

    PHP Warning:  File upload error - unable to create a temporary file in Unknown on line 0   我的测试环境是 w ...