Example of Yii2 framework to realize login and add verification code function
- 2021-10-25 06:04:28
- OfStack
In this paper, the Yii2 framework is used to realize the function of adding verification code when logging in. Share it for your reference, as follows:
In models
LoginForm.php
public $verifyCode;
public function rules()
{
return [
...
['verifyCode', 'captcha', 'on' => 'login'], // Verification code
];
}
public function scenarios() {
$scenarios = parent::scenarios();
$scenarios['login'] = ['username', 'password', 'rememberMe', 'verifyCode'];
return $scenarios;
}
In controller
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'width' => 100,
'height' => 34,
'padding' => 0,
'minLength' => 4,
'maxLength' => 4,
],
];
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm(['scenario' => 'login']);
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
In view
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
?>
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="input-group input-group-lg col-md-8"><span class="input-group-addon"><i class="glyphicon glyphicon-eye-open red"></i></span>{input}<div class="input-group-addon" style="padding:5px;">{image}</div></div>',
'options' => ['class' => 'form-control','placeholder'=>" Verification code "],
'imageOptions'=>['alt'=>' Click to change the picture ','title'=>' Click to change the picture ', 'style'=>'cursor:pointer']
])->label(false) ?>
<?php ActiveForm::end(); ?>
More readers interested in Yii can check the topics of this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Basic Tutorial of Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"
I hope this article is helpful to the PHP programming based on Yii framework.