search
HomePHP FrameworkYIIHow to log in to yii
How to log in to yiiDec 31, 2019 pm 02:56 PM
yii

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
            [[&#39;username&#39;, &#39;password&#39;], &#39;required&#39;,&#39;message&#39;=>""],
            // rememberMe must be a boolean value
            [&#39;rememberMe&#39;, &#39;boolean&#39;],
            // password is validated by validatePassword()
            [&#39;password&#39;, &#39;validatePassword&#39;],
        ];
    }
 
    /**
     * 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, &#39;Incorrect username or password.&#39;);
            }
        }
    }
 
    /**
     * 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 &#39;user&#39;;
	}

(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(&#39;index&#39;);
    }
 
    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(&#39;login&#39;, [      //⑤
            &#39;model&#39; => $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 = &#39;Login&#39;;
$this->params[&#39;breadcrumbs&#39;][] = $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([
        &#39;id&#39; => &#39;login-form&#39;,
        &#39;options&#39; => [&#39;class&#39; => &#39;form-horizontal&#39;],
        &#39;fieldConfig&#39; => [
            &#39;template&#39; => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
            &#39;labelOptions&#39; => [&#39;class&#39; => &#39;col-lg-1 control-label&#39;],
        ],
    ]); ?>
        <?= $form->field($model, &#39;username&#39;)->textInput([&#39;autofocus&#39; => true]) ?>
        <?= $form->field($model, &#39;password&#39;)->passwordInput() ?>
        <?= $form->field($model, &#39;rememberMe&#39;)->checkbox([
            &#39;template&#39; => "<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(&#39;Login&#39;, [&#39;class&#39; => &#39;btn btn-primary&#39;, &#39;name&#39; => &#39;login-button&#39;]) ?>
            </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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php如何使用Yii3框架?php如何使用Yii3框架?May 31, 2023 pm 10:42 PM

随着互联网的不断发展,Web应用程序开发的需求也越来越高。对于开发人员而言,开发应用程序需要一个稳定、高效、强大的框架,这样可以提高开发效率。Yii是一款领先的高性能PHP框架,它提供了丰富的特性和良好的性能。Yii3是Yii框架的下一代版本,它在Yii2的基础上进一步优化了性能和代码质量。在这篇文章中,我们将介绍如何使用Yii3框架来开发PHP应用程序。

如何使用PHP框架Yii开发一个高可用的云备份系统如何使用PHP框架Yii开发一个高可用的云备份系统Jun 27, 2023 am 09:04 AM

随着云计算技术的不断发展,数据的备份已经成为了每个企业必须要做的事情。在这样的背景下,开发一款高可用的云备份系统尤为重要。而PHP框架Yii是一款功能强大的框架,可以帮助开发者快速构建高性能的Web应用程序。下面将介绍如何使用Yii框架开发一款高可用的云备份系统。设计数据库模型在Yii框架中,数据库模型是非常重要的一部分。因为数据备份系统需要用到很多的表和关

Yii2 vs Phalcon:哪个框架更适合开发显卡渲染应用?Yii2 vs Phalcon:哪个框架更适合开发显卡渲染应用?Jun 19, 2023 am 08:09 AM

在当前信息时代,大数据、人工智能、云计算等技术已经成为了各大企业关注的热点。在这些技术中,显卡渲染技术作为一种高性能图形处理技术,受到了越来越多的关注。显卡渲染技术被广泛应用于游戏开发、影视特效、工程建模等领域。而对于开发者来说,选择一个适合自己项目的框架,是一个非常重要的决策。在当前的语言中,PHP是一种颇具活力的语言,一些优秀的PHP框架如Yii2、Ph

Symfony vs Yii2:哪个框架更适合开发大型Web应用?Symfony vs Yii2:哪个框架更适合开发大型Web应用?Jun 19, 2023 am 10:57 AM

随着Web应用需求的不断增长,开发者们在选择开发框架方面也越来越有选择的余地。Symfony和Yii2是两个备受欢迎的PHP框架,它们都具有强大的功能和性能,但在面对需要开发大型Web应用时,哪个框架更适合呢?接下来我们将对Symphony和Yii2进行比较分析,以帮助你更好地进行选择。基本概述Symphony是一个由PHP编写的开源Web应用框架,它是建立

Yii框架中的数据查询:高效地访问数据Yii框架中的数据查询:高效地访问数据Jun 21, 2023 am 11:22 AM

Yii框架是一个开源的PHPWeb应用程序框架,提供了众多的工具和组件,简化了Web应用程序开发的流程,其中数据查询是其中一个重要的组件之一。在Yii框架中,我们可以使用类似SQL的语法来访问数据库,从而高效地查询和操作数据。Yii框架的查询构建器主要包括以下几种类型:ActiveRecord查询、QueryBuilder查询、命令查询和原始SQL查询

yii如何将对象转化为数组或直接输出为json格式yii如何将对象转化为数组或直接输出为json格式Jan 08, 2021 am 10:13 AM

yii框架:本文为大家介绍了yii将对象转化为数组或直接输出为json格式的方法,具有一定的参考价值,希望能够帮助到大家。

Yii2编程指南:运行Cron服务的方法Yii2编程指南:运行Cron服务的方法Sep 01, 2023 pm 11:21 PM

如果您问“Yii是什么?”查看我之前的教程:Yii框架简介,其中回顾了Yii的优点,并概述了2014年10月发布的Yii2.0的新增功能。嗯>在这个使用Yii2编程系列中,我将指导读者使用Yii2PHP框架。在今天的教程中,我将与您分享如何利用Yii的控制台功能来运行cron作业。过去,我在cron作业中使用了wget—可通过Web访问的URL来运行我的后台任务。这引发了安全问题并存在一些性能问题。虽然我在我们的启动系列安全性专题中讨论了一些减轻风险的方法,但我曾希望过渡到控制台驱动的命令

Yii框架中的表单构建器:构建复杂表单Yii框架中的表单构建器:构建复杂表单Jun 21, 2023 am 10:09 AM

随着互联网的快速发展,Web应用越来越成为人们生活中不可或缺的一部分。而表单是Web应用中不可或缺的元素之一,其用于收集用户数据,让Web应用能够更好地为用户服务。Yii框架是一个快速、高效、灵活的PHP框架,可以帮助开发人员更加快速地开发Web应用。Yii框架中的表单构建器(FormBuilder)可以让开发人员轻松地构建复杂的表单,让Web应用具有更好

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment