我试图在yii2中生成一个验证码的验证码,而不是字符串。有什么办法吗?
发布于 2016-07-27 00:52:23
使用您自己的类扩展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
],
];
}其余部分与默认验证码完全相同。
https://stackoverflow.com/questions/38595349
复制相似问题