Originally thought Yii2 frame Verification code This piece is very comprehensive, try Baidu Google a bit, most of the tutorials write fragmented, thinking of their own write a full step of the verification Code tutorial.
We assume that the Site/login form login requires an increase in the authentication code.
1, the Sitecontroller controller's actions method increases the CAPTCHA setting
The Public Function actions () {return
[
' captcha ' => ['
class ' => ' Yii\captcha\captchaaction '
] MaxLength ' => 4,
' minlength ' => 4
],
];
}
Above we simply set the number of verification code, there are small partners curious about what configuration items, this 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, Sitecontroller continue to configure.
Public Function behaviors () {return
[
' Access ' => [
' class ' => accesscontrol::classname (),
' Rules ' => [['
actions ' => [' Login ', ' error ', ' Captcha '],
' Allow ' => true,
],
],
];
}
Add the Captcha method to the actions for access rules.
3, we look at the view layer, increase 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, this is not enough, we also need to increase the verification code validation rules
What we're using here is loginform, so modify the LoginForm file
Class LoginForm extends Model {
//... public $verifyCode;
Public Function rules () {return
[
//
...] [' Verifycode ', ' captcha '],
];
}
Public Function Attributelabels () {return
[
' Verifycode ' => ',//Verify code name, set according to personal preferences
];
}
//Defined Verifycode property
//rules Rules Add validation
5, to the fourth step basically configure the verification code will be normal display. If your background has a RBAC control, I'm afraid you still need to add/site/captcha to the as Accss in config.
6, see the effect is good.
7, a classmate asked why the page refresh verification code does not follow the refresh, I personally feel that the brush does not refresh is not important, when you get the wrong authentication code page refresh when the verification code will refresh. If you want to refresh the page verification code followed by refreshing, try a simple method implementation.
$ (' Authentication code object '). Click ();
That is, click the validation code again to force the refresh when the page is refreshed.
The above is a small series to introduce the YII2 to increase the verification code steps, I hope to help you!