Home > Article > PHP Framework > How to set the yii2 verification code style
How to set the yii2 verification code style
The first step, controller:
In Rewrite the method in any controller
public function actions() { return [ 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, 'backColor' => 0x000000,//背景颜色 'maxLength' => 6, //最大显示个数 'minLength' => 5,//最少显示个数 'padding' => 5,//间距 'height' => 40,//高度 'width' => 130, //宽度 'foreColor' => 0xffffff, //字体颜色 'offset' => 4, //设置字符偏移量 有效果 ], ]; }
The second step, form model:
Only the relevant parts of the verification code are given here.
Recommended related article tutorials: yii tutorial
class ContactForm extends Model{ public $verifyCode; public function rules(){ return [ ['verifyCode', 'required'], ['verifyCode', 'captcha'], ]; } }
The verifier for the verification code in the verification rules is captcha
.
The third step, view:
Use ActiveForm to generate the corresponding fields.
captchaAction
The parameter specifies where the first step is written. The default is inside site
.
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [ 'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>', ]) ?>
The entire process of verification code generation and verification is completed.
The above is the process of generating a verification code, because the verification code numbers are hard-coded in the code. What should we do if we need numbers?
It’s easy to do. We can write a class ourselves to inherit CaptchaAction and override the generateVerifyCode method. Example:
namespace yii\captcha; class Newcaptcha extends CaptchaAction { protected function generateVerifyCode() { if ($this->minLength > $this->maxLength) { $this->maxLength = $this->minLength; } if ($this->minLength < 3) { $this->minLength = 3; } if ($this->maxLength > 20) { $this->maxLength = 20; } $length = mt_rand($this->minLength, $this->maxLength); $letters = '1234567890123456789012'; $vowels = 'aeiou'; $code = ''; for ($i = 0; $i < $length; ++$i) { if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) { $code .= $vowels[mt_rand(0, 4)]; } else { $code .= $letters[mt_rand(0, 20)]; } } return $code; } }
The class file is generated successfully.
Then change the configuration of the controller
'captcha' => [ 'class' => 'yii\captcha\Newcaptcha', 'maxLength' => 5, 'minLength' =>5 ],
Okay, the change is completed, let’s take a look at the effect!
More For more knowledge about Yii framework, you can watch the related Programming Learning Course,! !
The above is the detailed content of How to set the yii2 verification code style. For more information, please follow other related articles on the PHP Chinese website!