yii2 captcha 和 verifycode 如何生成 unmber 没有任何字?

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

我正在尝试在 yii2 中使用数字而不是字符串形式的验证码生成验证码。 有什么办法吗?

用您自己的 class 扩展 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;
    }
}

在此示例中,class 保存在 common\captcha 文件夹中。如果您想将其保存在其他地方,请记住更改名称空间。

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

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

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