首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何生成yii2验证码和验证码?

如何生成yii2验证码和验证码?
EN

Stack Overflow用户
提问于 2016-07-27 00:33:15
回答 1查看 1.9K关注 0票数 6

我试图在yii2中生成一个验证码的验证码,而不是字符串。有什么办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-27 00:52:23

使用您自己的类扩展CaptchaAction并覆盖generateVerifyCode(),如下所示:

代码语言:javascript
复制
<?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文件夹中。如果您希望将名称空间保存到其他位置,请记住更改名称空间。

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

代码语言:javascript
复制
public function actions()
{
    return [
        'captcha' => [
            'class' => 'common\captcha\CaptchaAction', // change this as well in case of moving the class
        ],
    ];
}

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38595349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档