yii2 captcha not change on page refresh

喜欢而已 提交于 2020-04-13 06:13:10

问题


I am using the default captcha implementation of the yii2 advanced framework. I have a problem: I want to change my captcha code every time I refresh a page but when I refresh the page my captcha code does not change.


回答1:


The most correct solution will be to create your own CaptchaAction, that extends yii\captcha\CaptchaAction and override the run() method as follows:

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();
    }
}



回答2:


try this

<script>

window.onload = hello;

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

</script>



回答3:


because you have set YII_ENV to TEST like this defined('YII_ENV') or define('YII_ENV', 'test'); change it to defined('YII_ENV') or define('YII_ENV', 'prod');




回答4:


I found a dirty way round this - simply trigger the click event when the page loads. Add this code at the very end of your view file, after the end of the form;

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

It's not very pretty, but it works and it's the only way I've found to get aroun d this problem, which has also plagued my own sites.




回答5:


In your controller, just unset the session of captcha:

 session_start();
 unset($_SESSION["__captcha/panel/panel-auth/captcha"]);
 unset($_SESSION["__captcha/panel/panel-auth/captchacount"]);



回答6:


Update Your CaptchaAction as

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

Read Fixed Verify Code

IF fixedVerifyCode if set then captcha is same as value setted in 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];
}


来源:https://stackoverflow.com/questions/34401906/yii2-captcha-not-change-on-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!