How to generate yii2 captcha and verifycode without any words?

I am trying to create a captcha in yii2 with the verification code in the quantity indicated on the line. is there any way?

+6
source share
1 answer

Extend CaptchaAction with your own class and override generateVerifyCode() there, for example:

 <?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, the class is saved in the common\captcha folder. Remember to change the namespace if you want to save it elsewhere.

Now you just need to use it in the 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 as with the default captcha.

+5
source

All Articles