【问题标题】:How generate yii2 captcha and verifycode be unmber without any word?如何生成 yii2 验证码和验证码是无字的?
【发布时间】:2021-11-17 04:59:04
【问题描述】:

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

【问题讨论】:

    标签: security yii2 captcha


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 非常感谢。它为我工作。现在你能教我如何更改验证码的默认字体吗?
    • CaptchaAction 中有一个属性 - public $fontFile = '@yii/captcha/SpicyRice.ttf'; 所以你也可以在扩展类中覆盖它。
    • 请问您,如何没有ActiveForm输出和验证验证码?我的意思是,我不使用主动形式。但我想输出一个验证码并检查它。所以我可以在 actions() 方法中添加 captcha 然后呢? xD
    • @Adobe 您可以使用yii\helpers\Html 类生成的标准表单,并将独立的验证码作为小部件 (Captcha::widget()) - 其余部分相同。
    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多