How to log in to yii
yii Example of login method:
1. LoginForm.php
User login module, what is submitted is username and password, so we You need to first create a Model to specifically process the data submitted by users, so first create a new LoginForm.php. The following is the code:
<?php namespace app\modules\backend\models; use Yii; use yii\base\Model; /** * LoginForm is the model behind the login form. */ class LoginForm extends Model { public $username; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules()<span style="white-space:pre"> </span>//① { return [ // username and password are both required [['username', 'password'], 'required','message'=>""], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Incorrect username or password.'); } } } /** * Logs in a user using the provided username and password. * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { if($this->rememberMe) { $this->_user->generateAuthKey();//③ } return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); } return false; } /** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = User::findByUsername($this->username); //② } return $this->_user; } }
This Model is modified based on the LoginForm that comes with the basic template. Most of the code has Note, pay attention to the following code here:
The code number ① is the rules rule. The rules rules define the rules for the filled in data. Verify whether the filled in data is empty and conforms to the format. One of them The column is password, and the corresponding rule is validatePassword, which will automatically call the validatePassword() method of the current class. Pay attention to distinguishing it from the method corresponding to the User class below. Code
② calls the findByUsername method in the User class. This User class will be written below, mainly to return an AR class instance to compare with the current LoginForm data. The code number
③ will not be mentioned here for the time being. We will mention it later when we talk about cookie login.
2. User.php
(1) ActiveRecord class
After completing the LoginForm, we are still missing something. After receiving the data from the user, we still need to receive the data from the user. The database takes out the corresponding data for comparison, so what we need to complete next is a class for the data obtained from the database - the AR class, the full name is ActiveRecord, the active record class, which is convenient for finding data. As long as the class name and the data table are If the table names are the same, then it can get data from this data table, for example:
<?php namespace app\modules\backend\models; use yii\db\ActiveRecord; class User extends ActiveRecord{ } ?>
You can also add the returned table name yourself, just override the following method in this class:
public static function tableName(){ return 'user'; }
(2) IdentityInterface interface
Generally speaking, to find data from the database, you only need to inherit the AR class. However, ours is a user login model, and the core is verification, so it is natural to implement the core Verification function, just like validatePassword mentioned in the LoginForm model, the actual verification logic is completed in the current User model. Generally speaking, to implement the IdentityInterface interface, you need to implement the following methods:
public static function findIdentity($id); //① public static function findIdentityByAccessToken($token, $type = null); //② public function getId(); //③ public function getAuthKey(); //④ public function validateAuthKey($authKey); //⑤
①findIdentity: It is to find the data corresponding to the data table based on the id
②findIdentityByAccessToken is to find the corresponding data based on AccessToken (mentioned above) Data, and AccessToken we also have this field in the data table, so what is it used for? In fact, AccessToken is not very useful in our current user login model. It is specially used for Resetful login verification. The details can be found on Baidu. I will not explain it here.
③getId: Returns the id corresponding to the current AR class
④getAuthKey: Returns the auth_key corresponding to the current AR class
⑤validateAuthKey: This method is more important, which we will talk about later The core of cookie login verification is reached.
Implement the interface in our User.php, and then rewrite the above method. The complete User.php code is as follows:
$token]); } public static function findByUsername($username){ //① return static::findOne(['username'=>$username]); } public function getId(){ return $this->id; } public function getAuthkey(){ return $this->auth_key; } public function validateAuthKey($authKey){ return $this->auth_key === $authKey; } public function validatePassword($password){ //② return $this->password === md5($password); } /** * Generates "remember me" authentication key */ public function generateAuthKey() //③ { $this->auth_key = \Yii::$app->security->generateRandomString(); $this->save(); } } ?>
①findByUsername(): In the LoginForm code, this is quoted Method, the purpose is to return a data item that is the same as username in the data table, that is, an AR instance, based on the username submitted by the user.
②validatePassword(): Here, the password submitted by the user is compared with the password of the current AR class.
③generateAuthKey(): Generate a random auth_key for cookie login.
A total of two Model classes were written: LoginForm and User, one is used to receive data submitted by users, and the other is used to obtain data from the database.
Controller (Controller)
Controller is mainly used for data submission. It fills the data submitted by the user into the corresponding model (Model), and then Further render the view (View) based on the information returned by the model, or perform other logic.
Here, name the controller LoginController.php. The following is the complete implementation code:
<?php namespace app\controllers; use Yii; use yii\filters\AccessControl; use yii\web\Controller; use yii\filters\VerbFilter; use app\models\LoginForm; use app\models\ContactForm; class SiteController extends Controller { public function actionIndex() { return $this->render('index'); } public function actionLogin() { if (!\Yii::$app->user->isGuest) { //① return $this->goHome(); } $model = new LoginForm(); //② if ($model->load(Yii::$app->request->post()) && $model->login()) { //③ return $this->goBack(); //④ } return $this->render('login', [ //⑤ 'model' => $model, ]); } public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } }
① First judge from \Yii::$app->user->isGuest , whether it is currently in guest mode, that is, not logged in. If the user has logged in, the information of the currently logged in user will be stored in the user class.
②If you are currently a visitor, a LoginForm model will be instantiated first
③This line of code is the core of the entire login method. First: $model->load(Yii::$ app->request->post()) fills the post data into $model, that is, the LoginForm model. If true is returned, the filling is successful. Next: $model->login(): Execute the login() method in the LoginForm class. You can see from the login() method that a series of verifications will be performed.
View(View)
After implementing the model and controller, the next step is the view part. Since the user needs to input data, we have to provide a form. In Yii2, ActiveForm quick Generate the form, the code is as follows:
<?php /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model app\models\LoginForm */ use yii\helpers\Html; use yii\bootstrap\ActiveForm; $this->title = 'Login'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-login"> <h1><?= Html::encode($this->title) ?></h1> <p>Please fill out the following fields to login:</p> <?php $form = ActiveForm::begin([ 'id' => 'login-form', 'options' => ['class' => 'form-horizontal'], 'fieldConfig' => [ 'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>", 'labelOptions' => ['class' => 'col-lg-1 control-label'], ], ]); ?> <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?> <?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'rememberMe')->checkbox([ 'template' => "<div class=\"col-lg-offset-1 col-lg-3\">{input} {label}</div>\n<div class=\"col-lg-8\">{error}</div>", ]) ?> <div class="form-group"> <div class="col-lg-offset-1 col-lg-11"> <?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?> </div> </div> <?php ActiveForm::end(); ?> <div class="col-lg-offset-1" style="color:#999;"> You may login with <strong>admin/admin</strong> or <strong>demo/demo</strong>.<br> To modify the username/password, please check out the code <code>app\models\User::$users</code>. </div> </div>
Recommended learning: yii framework
The above is the detailed content of How to log in to yii. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands

With the rapid development of the Internet, APIs have become an important way to exchange data between various applications. Therefore, it has become increasingly important to develop an API framework that is easy to maintain, efficient, and stable. When choosing an API framework, Yii2 and Symfony are two popular choices among developers. So, which one is more suitable for API development? This article will compare these two frameworks and give some conclusions. 1. Basic introduction Yii2 and Symfony are mature PHP frameworks with corresponding extensions that can be used to develop

In modern software development, building a powerful content management system (CMS) is not an easy task. Not only do developers need to have extensive skills and experience, but they also need to use the most advanced technologies and tools to optimize their functionality and performance. This article introduces how to use Yii2 and GrapeJS, two popular open source software, to implement back-end CMS and front-end visual editing. Yii2 is a popular PHPWeb framework that provides rich tools and components to quickly build
