How to implement login form in Yii framework
In this post I will try to explain how to implement basic user login and logout actions for Yii framework 1.x skeleton application in. If you are working with Yii modules, than please read my post about How to separate logins for different Yii framework modules.
Let’s assume you already have a database containing a table called User
. User
table has the following columns:
Column name | Column type |
id | int |
firstName | char(15) |
lastName | char(15) |
username | char(20) |
password | char(30) |
userType | char(15) |
The first thing you should do is to generate User
model using Gii tool. Model is a PHP class that maps data from a database into PHP objects. Model allows you to fetch, update, delete rows from database in object oriented way. If you don’t know what is Gii and how to create a new model, please read this post.
When we have created a User
model, we can implement login functionality. Every login starts with basic login form. When you created your Yii application, you also generated a whole login functionality, which is not working with database, it is working with static values defined in array. Our job now is to make it work with database.
In your SiteController
there is an action called login
. Here is code:
1 2 3 4 5 6 7 8 |
$model = new LoginForm; if (isset($_POST['LoginForm'])) { $model->attributes = $_POST['LoginForm']; if ($model->validate() && $model->login()) $this->redirect(Yii::app()->user->returnUrl); } // display the login form $this->render('login', array('model' => $model)); |
In the first line we defined new LoginForm
object. In the second line we are checking if user submitted the form and if user submitted a login form, then get the values (username, password) and try to validate them and to login in with them:
1 |
if ($model->validate() && $model->login()) |
Methods validate()
and login()
are called on $model
object which type is LoginForm
, so let’s go to the LoginForm
class to see what is happening there.
In LoginForm
class which is saved under protected/models
let us concentrate on the login
action represented by the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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 ? 3600*24*30 : 0; // 30 days Yii::app()->user->login($this->_identity,$duration); return true; } else return false; } |
If identity
object is not defined, then create a new UserIdentity
object and assign it to $this->_identity
attribute. Ok, but what is this UserIdentity
class? This is the class where we will connect our Yii application with our User
database table, and make it work with database. How?
Open UserIdentity
class (protected/components/UserIdentity.php
) and you will see it is working with static array values. Instead of that, change your authenticate method with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public function authenticate() { $user=User::model()->findByAttributes(array("username"=>$this->username)); if(!isset($user)) $this->errorCode=self::ERROR_USERNAME_INVALID; else if($this->password != $user->password)//You should salt your password using CPasswordHelper $this->errorCode=self::ERROR_PASSWORD_INVALID; else{ $this->errorCode=self::ERROR_NONE; $this->setState("id", $user->id); $this->setState("firstName", $user->firstName); $this->setState("lastName", $user->lastName); $this->setState("userType", $user->userType); $user->save(); } return !$this->errorCode; } |
Let me try to explain what is happening here. In the first line you search for a user in a database using username. If user with provided username doesn’t exist, then set ERROR_USERNAME_INVALID
error code.
If user exists, then check it password. If password is not good, then set ERROR_PASSWORD_INVALID
error.
If user’s password is good, then save user’s id, first name, last name and user’s type to the session. Please note that user’s ID should always be stored in session never in a cookie.
Using userType
field we can distinguish user types. For example: administrators, editors, normal users should not have the same access rights etc…
Your job is finished here, because you connected UserIdentity
class with your database, and now you can log in using your username and password
For simplicity purposes, I didn’t want to complicate with password hashing, but you should definitely do that using CPasswordHelper
class in Yii framework.
If you want to check user type in any controller you can write something like this:
1 |
Yii::app()->user->getState('userType') |
If you want to logut user, then do this:
1 |
Yii::app()->user->logout(); |
http://code-epicenter.com/how-to-implement-login-form-in-yii-framework/How to implement login form in Yii frameworkPHPProgrammingTutorialsUncategorizedPHP,Yii frameworkIn this post I will try to explain how to implement basic user login and logout actions for Yii framework 1.x skeleton application in. If you are working with Yii modules, than please read my post about How to separate logins for different Yii framework modules. Let's assume you already have...Amir DuranAmir Duranamir.duran@gmail.comAdministratorAmir Duran is software engineer who currently lives and works in Germany. He obtained Masters degree diploma on Faculty of Electrical Engineering in Sarajevo, department Computer science. With good educational background he is specialized in designing and implementing a full-stack web based applications.Code Epicenter