如何生成yii2验证码和验证码没有任何单词?

Ami*_*min 6 security captcha yii2

我试图在yii2中生成一个验证码,并在字符串数字中生成验证码.有什么办法吗?

Biz*_*ley 5

CaptchaAction用你自己的类扩展并覆盖generateVerifyCode()那里:

<?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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,类保存在common\captcha文件夹中.如果要将命名空间保存在其他位置,请记住更改命名空间.

现在你只需要在控制器中使用它:

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

其余与默认验证码完全相同.