In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to achieve the login function in PHP's Yii framework, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.
Login Mechanism of Yii
Yii already provides the most basic user login mechanism when generating applications. We use Yii to generate a new application, enter the protected/components directory, we can see the UserIdentity.php file, in which there is only one public function in the UserIdentity class as follows:
Public function authenticate () {$users=array (/ / username = > password 'demo'= >' demo', 'admin'= >' admin',); if (! isset ($users [$this- > username])) $this- > errorCode=self::ERROR_USERNAME_INVALID; elseif ($users [$this- > username]! = = $this- > password) $this- > errorCode=self::ERROR_PASSWORD_INVALID; else $this- > errorCode=self::ERROR_NONE; return! $this- > errorCode;}
This class is in components and will be loaded at the beginning of the application for the most basic user authentication. As you can see, the function simply defines two users, demo and admin, and the password is only demo and admin. If so, if your users are very limited, you can directly modify and add users here, and we will talk about more later. The if else below the function is used to check whether the user name and password are valid, and generate ERROR_USERNAME_INVALID,ERROR_PASSWORD_INVALID when an error occurs. In general, the real user name and password verification is carried out here, and the basic logic processing after login is carried out.
If you look at this class alone, you can't see the login control process. Following the principles of Model/ Control/ View, we can see the login process in these three aspects. First go to the Models folder, you can see a LoginForm class file, this class inherits CFormModel, is a derived class of the form model, encapsulating the login data and business logic. The core functions are as follows:
/ * Authenticates the password. * This is the 'authenticate' validator as declared in rules (). * / public function authenticate ($attribute,$params) {$this- > _ identity=new UserIdentity ($this- > username,$this- > password); if (! $this- > _ identity- > authenticate ()) $this- > addError ('incorrect password',' username or password');} / * * Logs in the user using the given username and password in the model. * @ return boolean whether login is successful * / public function login () {if ($this- > _ identity===null) {$this- > _ identity=new UserIdentity ($this- > username,$this- > password); $this- > _ identity- > authenticate ();} if ($this- > _ identity- > errorCode===UserIdentity::ERROR_NONE) {$duration=$this- > rememberMe? 360024 hours 30: 0; / / 30 days Yii::app ()-> user- > login ($this- > _ identity,$duration); return true } else return false;}
The authenticate here uses the UserIdentity class to verify the user name and password, and the login function checks whether the user's identity has been set and the error code is empty, and finally logs in with the login function provided by Yii. $duration can set the validity period of the identity.
Let's take a look at Control. In siteControler, there is an action about login, which is actionLogin. The function is as follows:
/ * Displays the login page * / public function actionLogin () {if (! defined ('CRYPT_BLOWFISH') | |! CRYPT_BLOWFISH) throw new CHttpException (500, "This application requires that PHP was compiled with Blowfish support for crypt ()."); $model=new LoginForm; / / if it is ajax validation request if (isset ($_ POST [' ajax']) & & $POST ['ajax'] =' login-form') {echo CActiveForm::validate ($model) Yii::app ()-> end ();} / collect user input data if (isset ($_ POST ['LoginForm'])) {$model- > attributes=$_POST [' LoginForm']; / / validate user input and redirect to the previous page if valid if ($model- > validate () & & $model- > login ()) $this- > redirect (Yii::app ()-> user- > returnUrl) } / / display the login form $this- > render ('login',array (' model'= > $model));}
The action of the login is based on LoginForm to validate the POST form and login or render a new login page.
Finally, the view file is the login.php of the site folder, which is the login interface you see.
After combing, we can clearly see the user login logic processing of Yii. When you enter the user name and password in the login interface, the form POST the data to site/login. Loign instantiates a LoginForm form model and detects the login according to the validate function and login function in model. Validate will verify the form data according to the rules of rule, in which authenticate function is needed for password verification. The verification of authenticate and login functions is based on the authenticate function of UserIdentity. Therefore, if we change the login logic, both LgoinForm and loginaction can change the authenticate function of UserIdentity without modification.
The above analysis is the logic processing code automatically generated by Yii for user login. It already looks decent, doesn't it? But our system generally has to support a lot of user access, it is obviously irrational to simply list the user name and password in the code, and of course it is more mature to ask the database to help us manage it. Suppose we create an admin table in our own database with the following Mysql statement:
Drop table if exists `admin` Create table `admin` (`username` int unsigned not null auto_increment comment 'primary key', `username` varchar (32) not null comment 'login name', `psw`char (40) not null comment 'login password (twice sha1)', `nick`varchar (64) not null comment 'nickname', `add_ time`datetime not null comment 'creation time', `login_ time`datetime null comment 'recent login time', unique key (`username`), primary key (`admin_ id`) engine=innodb default charset=utf8 comment=' administrator table'
After the Mysql table is built, we use gii to generate the Model of admin, and then we can go back to the UserIdentity.php rewrite authenticate function in our original Component to implement our own username and password verification. For security reasons, the password is encrypted twice by sha1, so the collected password is encrypted twice by sha1, then find out whether there is a user corresponding to the username entered in the form in the Admin we created, and then compare the encrypted password. If all passwords are passed, you can set the common information of this user from the setState function to the user field of Yii's user, such as $this- > setState ('nick', $user- > nick). After this sentence, you can later access the nickname of the currently logged-in user directly through Yii:app ()-> user- > nick without having to query the database. On the other hand, $user- > login_time = date ('Y-m-d Hlav idate'); is to update the user login time and save it to the database through the save of the next sentence.
Public function authenticate () {if (strlen ($this- > password) > 0) $this- > password = sha1 (sha1 ($this- > password)); $user = Admin::model ()-> findByAttributes (array ('username' = > $this- > username); if ($user = = null) $this- > errorCode=self::ERROR_USERNAME_INVALID; elseif (! ($user instanceof Admin) | | ($user- > psw! = $this- > password)) $this- > errorCode=self::ERROR_PASSWORD_INVALID Else {$this- > setState ('admin_id', $user- > admin_id); $this- > setState (' nick', $user- > nick); $this- > setState ('username', $user- > username); $user- > login_time = date (' Y-m-d HaviRangs'); $user- > save (); $this- > errorCode=self::ERROR_NONE;} return! $this- > errorCode;}
If you want to change the login interface, go to the login.php in the site folder in view and make it what you want, so that our own login process is complete. Is it very convenient to have Yii?
Set up automatic login
The principle of automatic login is simple. It is mainly realized by using cookie
On the first login, if the login is successful and the next automatic login is selected, the user's authentication information will be saved to cookie, and the cookie will be valid for 1 year or several months.
Determine whether the user's information is stored in cookie the next time you log in, and if so, log in with the user information stored in cookie.
Configure User components
First set the user component in the components of the configuration file
'user' = > [' identityClass' = > 'app\ models\ User',' enableAutoLogin' = > true,]
We see that enableAutoLogin is used to determine whether to enable automatic login, which has nothing to do with the next automatic login on the interface.
Only if enableAutoLogin is true, if the next automatic login is selected, the user information will be stored in cookie and the validity period of cookie will be set to 360024030 seconds for the next login.
Now let's take a look at how it is implemented in Yii.
Log in and save cookie for the first time
1. Login login function
Public function login ($identity, $duration = 0) {if ($this- > beforeLogin ($identity, false, $duration)) {$this- > switchIdentity ($identity, $duration); $id = $identity- > getId (); $ip = Yii::$app- > getRequest ()-> getUserIP (); Yii::info ("User'$id' logged in from $ip with duration $duration.", _ _ METHOD__); $this- > afterLogin ($identity, false, $duration);} return! $this- > getIsGuest ();}
In this case, simply log in, and then execute the switchIdentity method to set the authentication information.
2. Set authentication information for switchIdentity
Public function switchIdentity ($identity, $duration = 0) {$session = Yii::$app- > getSession (); if (! YII_ENV_TEST) {$session- > regenerateID (true);} $this- > setIdentity ($identity); $session- > remove ($this- > idParam); $session- > remove ($this- > authTimeoutParam); if ($identity instanceof IdentityInterface) {$session- > set ($this- > idParam, $identity- > getId ()) If ($this- > authTimeout! = = null) {$session- > set ($this- > authTimeoutParam, time () + $this- > authTimeout);} if ($duration > 0 & & $this- > enableAutoLogin) {$this- > sendIdentityCookie ($identity, $duration);} elseif ($this- > enableAutoLogin) {Yii::$app- > getResponse ()-> getCookies ()-> remove (new Cookie ($this- > identityCookie));}}
This method is important and needs to be called when you exit.
This method has three main functions.
Set the validity period of session
If the validity period of cookie is greater than 0 and automatic login is allowed, then the user's authentication information is saved to cookie.
If automatic login is allowed, delete the cookie information. This is called on exit. The $identity passed in when exiting is null
Protected function sendIdentityCookie ($identity, $duration) {$cookie = new Cookie ($this- > identityCookie); $cookie- > value = json_encode ([$identity- > getId (), $identity- > getAuthKey (), $duration,]); $cookie- > expire = time () + $duration; Yii::$app- > getResponse ()-> getCookies ()-> add ($cookie);}
The user information stored in cookie contains three values:
$identity- > getId ()
$identity- > getAuthKey ()
$duration
GetId () and getAuthKey () are in the IdentityInterface interface. We also know that when setting up the User component, this User Model must implement the IdentityInterface interface. So, you can get the first two values in User Model, and the third value is the validity period of cookie.
Log in automatically from cookie
From the above, we know that the user's authentication information has been stored in cookie, so next time, just take the information from cookie and set it.
1. AccessControl user access control
Yii provides AccessControl to determine whether a user is logged in, so there is no need to judge in every action.
Public function behaviors () {return ['access' = > [' class' = > AccessControl::className (), 'only' = > [' logout'], 'rules' = > [' actions' = > ['logout'],' allow' = > true, 'roles' = > [' @'],];}
2. GetIsGuest and getIdentity determine whether to authenticate the user.
IsGuest is the most important attribute in the automatic login process.
In the above AccessControl access control, use the IsGuest attribute to determine whether it is an authenticated user, and then call getIdentity in the getIsGuest method to obtain user information. If it is not empty, it means an authenticated user, otherwise it is a tourist (not logged in).
Public function getIsGuest ($checkSession = true) {return $this- > getIdentity ($checkSession) = null;} public function getIdentity ($checkSession = true) {if ($this- > _ identity = false) {if ($checkSession) {$this- > renewAuthStatus ();} else {return null;}} return $this- > _ identity;}
3. RenewAuthStatus regenerates user authentication information
Protected function renewAuthStatus () {$session = Yii::$app- > getSession (); $id = $session- > getHasSessionId () | | $session- > getIsActive ()? $session- > get ($this- > idParam): null; if ($id = null) {$identity = null;} else {/ * * @ var IdentityInterface $class * / $class = $this- > identityClass; $identity = $class::findIdentity ($id);} $this- > setIdentity ($identity) If ($this- > authTimeout! = = null & & $identity! = = null) {$expire = $session- > get ($this- > authTimeoutParam); if ($expire! = = null & & $expire
< time()) { $this->Logout (false);} else {$session- > set ($this- > authTimeoutParam, time () + $this- > authTimeout);}} if ($this- > enableAutoLogin) {if ($this- > getIsGuest ()) {$this- > loginByCookie ();} elseif ($this- > autoRenewCookie) {$this- > renewIdentityCookie ();}
This section first uses session to determine the user, because the user already exists in session after logging in. Then determine if it is an automatic login, then log in through the cookie information.
4. Log in to loginByCookie through the saved Cookie information
Protected function loginByCookie () {$name = $this- > identityCookie ['name']; $value = Yii::$app- > getRequest ()-> getCookies ()-> getValue ($name); if ($value! = = null) {$data = json_decode ($value, true); if (count ($data) = = 3 & & isset ($data [0], $data [1], $data [2])) {list ($id, $authKey, $duration) = $data / * * @ var IdentityInterface $class * / $class = $this- > identityClass; $identity = $class::findIdentity ($id); if ($identity! = = null & & $identity- > validateAuthKey ($authKey)) {if ($this- > beforeLogin ($identity, true, $duration)) {$this- > switchIdentity ($identity, $this- > autoRenewCookie? $duration: 0); $ip = Yii::$app- > getRequest ()-> getUserIP () Yii::info ("User'$id' logged in from $ip via cookie.", _ _ METHOD__); $this- > afterLogin ($identity, true, $duration);}} elseif ($identity! = = null) {Yii::warning ("Invalid auth key attempted for user'$id': $authKey", _ _ METHOD__);}
Read the cookie value first, and then $data = json_decode ($value, true); deserialize it into an array.
You can see from the above code that in order to achieve automatic login, all three values must have values. In addition, findIdentity and validateAuthKey must be implemented in User Model.
After logging in, you can also reset the validity period of cookie, so that it can be valid together.
$this- > switchIdentity ($identity, $this- > autoRenewCookie? $duration: 0)
3. Quit logout
Public function logout ($destroySession = true) {$identity = $this- > getIdentity (); if ($identity! = = null & & $this- > beforeLogout ($identity)) {$this- > switchIdentity (null); $id = $identity- > getId (); $ip = Yii::$app- > getRequest ()-> getUserIP (); Yii::info ("User'$id' logged out from $ip.", _ _ METHOD__); if ($destroySession) {Yii::$app- > getSession ()-> destroy () } $this- > afterLogout ($identity);} return $this- > getIsGuest ();} public function switchIdentity ($identity, $duration = 0) {$session = Yii::$app- > getSession (); if (! YII_ENV_TEST) {$session- > regenerateID (true);} $this- > setIdentity ($identity); $session- > remove ($this- > idParam); $session- > remove ($this- > authTimeoutParam) If ($identity instanceof IdentityInterface) {$session- > set ($this- > idParam, $identity- > getId ()); if ($this- > authTimeout! = = null) {$session- > set ($this- > authTimeoutParam, time () + $this- > authTimeout);} if ($duration > 0 & $this- > enableAutoLogin) {$this- > sendIdentityCookie ($identity, $duration) }} elseif ($this- > enableAutoLogin) {Yii::$app- > getResponse ()-> getCookies ()-> remove ($this- > identityCookie);}}
When you exit, first set the current authentication to null, and then determine that if it is an automatic login function, then delete the relevant cookie information.
Thank you for reading this article carefully. I hope the article "how to achieve login function in PHP's Yii framework" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.