验证码不能使用yii2中的方案

时间:2018-05-23 14:28:52

标签: yii2 yii2-advanced-app yii2-model yii2-user yii2-validation

我正在尝试根据场景添加验证码验证,我首先从数据库中检索失败尝试次数。我正在使用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,
                ]);
    }

在我的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 } ?>

在我的控制器中,当我在$ model-&gt; login()函数中打印模型错误时,即使验证码正确,它也会在每次都给出以下错误。

Array ( [verifycode] => Array ( [0] => The verification code is incorrect. ) )

为什么每次都失败了。代码中是否有任何错误?

提前致谢

0 个答案:

没有答案