使用yii2中的场景验证码不起作用

使用yii2中的场景验证码不起作用,yii2,yii2-advanced-app,yii2-model,yii2-user,yii2-validation,Yii2,Yii2 Advanced App,Yii2 Model,Yii2 User,Yii2 Validation,我尝试根据场景添加验证码验证,首先从数据库检索失败尝试的次数。我正在为其使用checkattempts()函数。根据结果,我在视图中显示验证码,并在控制器中添加场景条件,如下所示 在LoginForm模型中: public function rules() { return [ [['username', 'password'], 'required', 'on'=>'loginpage'], [['username', 'password'], '

我尝试根据场景添加验证码验证,首先从数据库检索失败尝试的次数。我正在为其使用
checkattempts()
函数。根据结果,我在视图中显示验证码,并在控制器中添加场景条件,如下所示

在LoginForm模型中:

public function rules()
{
    return [
        [['username', 'password'], 'required', 'on'=>'loginpage'],
        [['username', 'password'], 'required', 'on'=>'withCaptcha'],
        [['reference_url'], 'safe'],
        [['verifyCode'], 'captcha', 'skipOnEmpty' => true,'on'=>'withCaptcha'],         
        ['username','email', 'on'=>'loginpage', 'message'=> 'Please enter a valid email address'],
        ['password', 'validatePassword', 'on'=>'loginpage'],
        ['password', 'validatePassword', 'on'=>'withCaptcha'],
    ];
}

 public function checkattempts($uname)
{
    $user = \frontend\models\User::findByEmail($uname);
    $ip = $this->get_client_ip();
    if($user){
    $data = (new Query())->select('*')  
                ->from('login_attempts')
                ->where(['ip' => $ip])->andWhere(['user_ref_id' => $user->id])
                ->one();
    if($data["attempts"] >=3){
        return true;
    }else{
        return false;
    }
    }
    return false;
}
在SiteController.php控制器中

 public function actionLogin() {
    if (!\Yii::$app->user->isGuest) {
        return $this->redirect(Yii::$app->getUrlManager()->getBaseUrl() . '/../../');
    }
    $model = new \common\models\LoginForm();
    $model->scenario = 'loginpage';
    $captcha = false;
    if(Yii::$app->request->post()){
    $post_variables =Yii::$app->request->post('LoginForm');         
        if ($model->checkattempts($post_variables['username'])) {
            $model->scenario = 'withCaptcha'; 
            $captcha = true;
        }
    }
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         $model->login(); print_r($model->getErrors()); exit;
    } else {
        return $this->render('login', [
                    'model' => $model, 'captcha' => $captcha,
                ]);
    }
在my login.php视图中:

 <?php if($captcha) { ?>
            <?= $form->field($model, 'verifyCode')->widget(Captcha::className(), 
        ['template' => '<div class="captcha_img">{image}</div>'
            . '<a class="refreshcaptcha" href="#">'
            . Html::img('/images/imageName.png',[]).'</a>'
            . 'Verification Code{input}',
        ])->label(FALSE); ?>   
            <?php } ?>
为什么每次都失败。写的代码有错误吗


提前感谢

我认为您的代码存在一些设计问题,您的代码过于复杂了。为什么要计算IP和用户的故障,而不仅仅是IP故障?这不太安全(一个IP攻击者可以进行数千次尝试-他可以在3次失败后切换受攻击的用户),而且更难实现,因为您不知道是否应该在填写表单之前显示验证码。Google reCAPTCHA比yii\captcha\captcha更安全。尝试使用扩展。你解决了这个问题吗?
Array ( [verifycode] => Array ( [0] => The verification code is incorrect. ) )