第一种方法(失败):
修改 fixedVerifyCode 值,确实可以刷新页面的时候改变验证码,
但是 Session 里面没有值,没有值,没有值…
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => substr(str_shuffle('ABCDEFGHJKMNPQRSTUVWXY3456789'),0,6),
'maxLength' => 6, //最大显示个数
'minLength' => 5,//最少显示个数
'padding' => 0,//间距
'height'=>40,//高度
'width' => 130, //宽度
'offset'=>-2, //设置字符偏移量 有效果
],
];
}
1,
第二种方法(成功),网上大部分都是这个解决方案,修改 vendor\yiisoft\yii2\captcha\CaptchaAction.php 里面的源代码,如下图:
第三种方法(成功):重写 yii\captcha\CaptchaAction 里面的run方法,其实和第二种雷同,只是不改源代码而已
<?php
namespace common\componets;
/**
* 重写验证码
* @package common\componets
*/
use Yii;
use yii\base\Action;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\web\Response;
class Mycaptcha extends \yii\captcha\CaptchaAction
{
public function run()
{
if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
// AJAX request for regenerating code
$code = $this->getVerifyCode(true);
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'hash1' => $this->generateValidationHash($code),
'hash2' => $this->generateValidationHash(strtolower($code)),
// we add a random 'v' parameter so that FireFox can refresh the image
// when src attribute of image tag is changed
'url' => Url::to([$this->id, 'v' => uniqid()]),
];
} else {
$this->setHttpHeaders();
Yii::$app->response->format = Response::FORMAT_RAW;
return $this->renderImage($this->getVerifyCode(true));
}
}
}
调用的代码
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'common\componets\Mycaptcha',
'maxLength' => 6, //最大显示个数
'minLength' => 5,//最少显示个数
'padding' => 0,//间距
'height'=>40,//高度
'width' => 130, //宽度
'offset'=>-2, //设置字符偏移量 有效果
],
];
}
纠结:
个人以为第一种方法应该是最理想的方案,但SESSION里面却没有对应的值,不知是否我还有哪里没有配置好?
第二种和第三种方法,总感觉验证码这样基本功能都需要动到源代码的话,会不会感觉这个框架有点弱?
还是说框架的设计者原本就是这样设计的,刷新页面的时候不刷新验证码,如果是这样的话,想知道为什么要这样设计
注:看了这个 https://github.com/yiisoft/yii2/issues/10071#event-458678122 但奈何英文太弱了,翻译下面的回答还是不理解;