[yii2] Create a Login Form with Captcha

17 April 2021

Home » Blogs » Technology » [yii2] Create a Login Form with Captcha

Adding a to the login form is quite easy and can be done in three steps:

  1. In models/LoginForm.php you must add fields and validation rules.
  2. In views/site/login.php you have to put a field.
  3. In controllers/SiteController.php you’ll need to add captcha action.

In this tutorial, I want to show you how to create a captcha in the login form, but you can add a captcha to any form by following these steps.

TOP TUTORIALS:  [yii2] Show captcha after failed login attempt

1. Add captcha fields and validation rules to models/LoginForm.php

First of all, you need to change the login form as described above. Then, you’ll need to add a public property called verifyCode and its validation rules.

class LoginForm extends Model
{
    .............
    .............
    public $verifyCode;
    .............
  
    public function rules()
    {
        return [
            .............
            .............
  
            ['verifyCode', 'required', 'when'=>function(){return $this->loginFailed;}],
            ['verifyCode', 'captcha', 'when'=>function(){return $this->loginFailed;}],
              
            .............
            .............
        ];
    }
 
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            .............
            if (!$user || !$user->validatePassword($this->password)) {
 
                Yii::$app->session->set('_loginAttempts', Yii::$app->session->get('_loginAttempts', 0)+1);
 
                .............
            }
        }
    }   
     
    //Check number login failed
    public function getLoginFailed()
    {
        return Yii::$app->session->get('_loginAttempts', 0) > 3;
    }
     
    .............
    .............   
}

2. Add widgets to views/site/login.php

.............
.............
 
............. .............
'login-form']); ?> ............. ............. loginFailed){ echo $form->field($model, 'verifyCode')->widget(\yii\captcha\Captcha::class); } ?> ............. .............

3. Add action to the controller/SiteController.php

For captchas to work, you’ll need to add an action captcha to controllers/SiteController.php. Maybe the action already exists because the standard Yii2 app template adds it automatically.

.............
.............
  
class SiteController extends Controller
{
    .............
    .............
      
    public function actions()
    {
        return [
            .............
            .............
              
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
            ],
            .............
            .............
        ];
    }
      
    .............
    .............   
}

0 Comments