Detailed steps for adding a verification code to Yii2 and detailed steps for yii2 Verification Code
I thought the yii2 framework verification code was comprehensive. I tried Baidu and google. Most of the tutorials were not completely scattered. I thought I would write a verification code tutorial with the complete steps.
We assume that you need to add a verification code to log on to the site/login form.
1. Added captcha settings for the actions method of siteController
public function actions() { return [ 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'maxLength' => 4, 'minLength' => 4 ], ]; }
We have simply set the number of digits of the Verification Code. Some friends are curious about the configuration items. You can view the file vendor \ yiisoft \ yii2 \ captcha, including the background color of the verification code, font files and other settings can be found here.
2. Configure siteController.
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['login', 'error', 'captcha'], 'allow' => true, ], ], ]; }
Add the captcha method to access the actions of the access rules.
3. Let's look at the view layer and add the verification code input.
use yii\captcha\Captcha; <?= $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>', ]) ?>
4. We still need to add verification rules for verification codes.
We use LoginForm here, so we need to modify the LoginForm file.
Class LoginForm extends Model {//...... public $ verifyCode; public function rules () {return [//...... ['verifycode', 'captcha '],];} public function attributeLabels () {return ['verifycode' => '', // verification code name, set according to your preferences];} // defines the verifyCode attribute // The display name is defined in the verifyCode rule added validation // label
5. In Step 4, the verification code is displayed normally after the verification code is configured. If rbac permission control is set in your background, I am afraid you still need to add/site/captcha for access to the as accss in config.
6. Check the effect.
7. Some people asked why the verification code is not refreshed on the page. I personally think it is not important to refresh it. The verification code is refreshed only when you enter the Incorrect verification code page. If you have to refresh the page verification code and refresh it, try a simple method.
$ ('Verification code object'). click ();
That is, when the page is refreshed, click the verification code again to force the refresh.
The above section describes how to add a verification code to Yii2. I hope it will help you!