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

bardimin pic

Written by Bardimin

On April 21, 2021
Home » Blogs » Technology » [yii2] How to refresh a captcha with a button or reload a page

By default, Yii2 does not come with a “refresh” link/button that allows you to refresh 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 commons\models 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 to the login function in the controller / SiteController.php

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

Latest Articles

Basic Computer and Laptop Maintenance Techniques

Basic Computer and Laptop Maintenance Techniques

You may not realize it, but computers and cars have something in common, both requiring regular maintenance. If your car needs regular oil changes, your computer should also regularly update its software, keep its antivirus up to date, and check for spyware....

The desktop version of ChatGPT for Windows, Linux, and Mac

The desktop version of ChatGPT for Windows, Linux, and Mac

Do you know what ChatGPT is? Do you know how to get and install ChatGPT on your device? ChatGPT is fast becoming one of the most important inventions in the world of natural language processing. You can use it to generate human-like responses based on your input. You...

24 Pinout Voltage at ATX Power Supply to the Motherboard

24 Pinout Voltage at ATX Power Supply to the Motherboard

The Power Supply converts alternating current (AC) power into low-voltage controlled direct current (DC). Some Power Supply devices include a choice of manual input voltages, while others automatically adjust. The Power Supply converts the voltage from the power line...

Google Chrome – Open Bookmarks to a New Tab By Default

Google Chrome – Open Bookmarks to a New Tab By Default

Bookmarks are shortcuts to open website pages that you have saved for you to visit again later. Have you ever visited a website page that is quite interesting and you want to visit it again later? Considering the address of a website page is certainly difficult,...

x