[yii2] How to refresh a captcha with a button or reload a page

By default, Yii2 captcha does not come with a “refresh” link/button that allows you to refresh captcha images. Likewise, when reloading the captcha image page, that appears remains the same. This can frustrate because often captcha images are unreadable (even by humans).

In this tutorial, we will learn to create a link/button to “refresh” captcha images and also refresh captcha images every time they reload the page.

1. Create CaptchaRefreshable

The first step we need to do is to create a CaptchaRefreshable class in the models directory or commons\models if you are using the yii2 advanced template.

<?php
 
namespace common\models;
 
class CaptchaRefreshable extends \yii\captcha\Captcha
{
    /**
     * Overrides the $template HTML
     */
    public function init()
    {
        $refresh_a = \yii\helpers\Html::a('refresh', '#', [
            'id' => 'refresh-captcha',
            'class' => 'text-small' // .text-small { font-size: 0.85em; } - include in your CSS
        ]);
 
        $this->template = '
            <div id="verify-code" class="row">
            <div class="large-3 columns">{image} ' . $refresh_a . '</div>
            <div class="large-6 columns">{input}</div>
            </div>';
        parent::init();
    }
 
    /** 
     * Register the refresh JS 
     */
    public function registerClientScript()
    {
        $view = $this->getView();
        $view->registerJs(" $('#refresh-captcha').on('click', function(e){ e.preventDefault(); $('#verify-code img').yiiCaptcha('refresh'); }) ");
        parent::registerClientScript();
    }
}

2. Create CaptchaRefreshableAction

Then we create a CaptchaRefreshableAction class in the models directory or commonsmodels if you are using the yii2 advanced template.

<?php
 
 
namespace common\models;
 
use Yii;
 
 
class CaptchaRefreshableAction extends \yii\captcha\CaptchaAction
{
    public function validate($input, $caseSensitive)
    {
        // Skip validation on AJAX requests, as it expires the captcha.
        if (Yii::$app->request->isAjax) {
            return true;
        }
        return parent::validate($input, $caseSensitive);
    }
 
}

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

.............
.............
 
<div class="site-login">
    .............
    .............
 
    <div class="row">
        <div class="col-lg-5">
            <?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
 
                .............
                .............
 
                <?= $form->field($model, 'verifyCode')->widget(\common\models\CaptchaRefreshable::class) ?>
 
                .............
                .............
     
            <?php ActiveForm::end(); ?>
        </div>
    </div>
</div>

4. Add action to the controller/SiteController.php

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

5. Add action to refresh captcha on page reload

In steps 1-4 above, we have created a button/link to refresh the captcha image. The problem is that when reloading the page, the captcha image displayed does not change. In order for the captcha image to change every reload page, we need to add a script to the login function in the controller / SiteController.php

.............
.............
  
class SiteController extends Controller
{
    .............
    .............
      
    public function actionLogin()
    {
 
        $this->createAction('captcha')->getVerifyCode(true);
 
        .............
        ............. 
     
    }
      
    .............
    .............   
}

Latest Articles