Php 页面刷新时未更改yii2验证码

Php 页面刷新时未更改yii2验证码,php,yii2,yii2-advanced-app,Php,Yii2,Yii2 Advanced App,我使用的是yii2高级框架的默认验证码实现。我有一个问题:每次刷新页面时,我都想更改验证码,但当我刷新页面时,我的验证码不会更改。将您的验证码操作更新为 public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' =&

我使用的是yii2高级框架的默认验证码实现。我有一个问题:每次刷新页面时,我都想更改验证码,但当我刷新页面时,我的验证码不会更改。

将您的
验证码操作更新为

public function actions()
{
    return [
        'error' => [
            'class' => 'yii\web\ErrorAction',
        ],
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
            'fixedVerifyCode' => null,
        ],
    ];
}
阅读

如果设置了
fixedVerifyCode
,则验证码与
fixedVerifyCode

// code from yii\captcha\CaptchaAction in Yii2

public function getVerifyCode($regenerate = false)
{
    if ($this->fixedVerifyCode !== null) {
        return $this->fixedVerifyCode;
    }

    $session = Yii::$app->getSession();
    $session->open();
    $name = $this->getSessionKey();
    if ($session[$name] === null || $regenerate) {
        $session[$name] = $this->generateVerifyCode();
        $session[$name . 'count'] = 1;
    }

    return $session[$name];
}

我发现了一个不好的解决方法——当页面加载时,只需触发
click
事件。将此代码添加到
视图
文件的最末尾,在表单末尾之后

$js = <<<JS
       $('#loginform-captcha-image').trigger('click');
JS;
$this->registerJs($js, $this::POS_READY);

$js=最正确的解决方案是创建自己的
CaptchaAction
,它扩展了
yii\captcha\CaptchaAction
并覆盖
run()
方法,如下所示:

namespace app\actions; // Change to your own    

class CaptchaAction extends yii\captcha\CaptchaAction {
    public $autoRegenerate = true;

    public function run() 
    {
       if ($this->autoRegenerate && Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) === null) {
           $this->setHttpHeaders();
           Yii::$app->response->format = Response::FORMAT_RAW;
           return $this->renderImage($this->getVerifyCode(true));
       }
       return parent::run();
    }
}

因为您已经将yi_ENV设置为这样的测试
defined('yi_ENV')或define('yi_ENV','TEST')将其更改为
defined('yi_ENV')或define('yi_ENV','prod')

试试这个

<script>

window.onload = hello;

function hello()
{    
  document.getElementById('loginform-captcha-image').click();
}

</script>

window.onload=hello;
函数hello()
{    
document.getElementById('loginform-captcha-image')。单击();
}

在控制器中,只需
取消设置验证码会话:

 session_start();
 unset($_SESSION["__captcha/panel/panel-auth/captcha"]);
 unset($_SESSION["__captcha/panel/panel-auth/captchacount"]);
这对我有用

$(document).ready(function(){
  setTimeout(() => {
    $("#form-captcha-image").click();
  }, 100);  
});

很可能验证码存储在现金中,请编辑问题并发布一些代码,否则问题将被关闭,请参阅帮助中心。无需发布任何代码。我使用默认的验证码实现。这将不起作用,因为
fixedVerifyCode
被设置为标准。当您这样做时,似乎一切正常,但当您想使用刷新链接刷新代码时,出现了一个问题,因为刷新链接会重新生成代码并在客户端中获得新的哈希值以进行验证当图像请求时,它也会重新生成代码,这样验证哈希就无效了