logo
当前位置:首 页 > 编程技术 >后端开发 >PHP语言 > 查看文章

第一种方法(失败):

修改 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 但奈何英文太弱了,翻译下面的回答还是不理解;

说说梦想,谈谈感悟 ,聊聊技术,有啥要说的来github留言吧 https://github.com/cjx2328

—— 陈 建鑫

陈建鑫
footer logo
未经许可请勿自行使用、转载、修改、复制、发行、出售、发表或以其它方式利用本网站之内容。站长联系:cjx2328#126.com(修改#为@)
Copyright ©ziao Studio All Rights Reserved. E-mail:cjx2328#126.com(#号改成@) 沪ICP备14052271号-3