【发布时间】:2021-11-17 04:59:04
【问题描述】:
我正在尝试在 yii2 中使用数字而不是字符串中的验证码生成验证码。 有什么办法吗?
【问题讨论】:
我正在尝试在 yii2 中使用数字而不是字符串中的验证码生成验证码。 有什么办法吗?
【问题讨论】:
用你自己的类扩展 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
],
];
}
其余与默认验证码完全相同。
【讨论】:
public $fontFile = '@yii/captcha/SpicyRice.ttf'; 所以你也可以在扩展类中覆盖它。
yii\helpers\Html 类生成的标准表单,并将独立的验证码作为小部件 (Captcha::widget()) - 其余部分相同。