Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How generate yii2 captcha and verifycode be unmber without any word?

I am trying to generate a captcha in yii2 with a verify code in number instead of string. is there any way?

like image 315
Aminkt Avatar asked Jul 26 '16 16:07

Aminkt


1 Answers

Extend CaptchaAction with your own class and override generateVerifyCode() there like:

<?php

namespace common\captcha;

use yii\captcha\CaptchaAction as DefaultCaptchaAction;

class CaptchaAction extends DefaultCaptchaAction
{
    protected function generateVerifyCode()
    {
        if ($this->minLength > $this->maxLength) {
            $this->maxLength = $this->minLength;
        }
        if ($this->minLength < 3) {
            $this->minLength = 3;
        }
        if ($this->maxLength > 8) {
            $this->maxLength = 8;
        }
        $length = mt_rand($this->minLength, $this->maxLength);
        $digits = '0123456789';
        $code = '';
        for ($i = 0; $i < $length; ++$i) {
            $code .= $digits[mt_rand(0, 9)];
        }
        return $code;
    }
}

In this example class is saved in common\captcha folder. Remember to change the namespace if you would like to save it somewhere else.

Now you just need to use it in controller:

public function actions()
{
    return [
        'captcha' => [
            'class' => 'common\captcha\CaptchaAction', // change this as well in case of moving the class
        ],
    ];
}

The rest is exactly the same like with default captcha.

like image 100
Bizley Avatar answered Oct 03 '22 11:10

Bizley