Yii 1.1: How to get & store Last Login DateTime in database?


In this wiki I will show how could be store last login date & time in database. First we need a field LastLoginTime (Type must be datetime). this field store a user login detalis (like - Date & Time).

In your components

Create a file called WebUser.php into components directory. In which needs to define the WebUser class, which should be an extension of the Yii CWebUser class. Within that class, we will defined a method afterLogin(), eg. -

class WebUser extends CWebUser {
    public function afterLogin()
        if (parent::beforeLogout()) {
            $user = User::model()->findByPk(Yii::app()->user->id);
            $user->LastLoginTime=date('Y-m-d H:i:s');
            return true;
        } else {
            return false;

In Your config main.php

Need to set WebUser class in user array -


eg. -

// application components
          'class'=>'WebUser',  //Adding WebUser class
          'autoRenewCookie' => true,
               'loginUrl' => array('site/login'),

In your UserIdentity.php

Set the last login time in varible lastLoginTime in authenticate() function after successfully authentication.

public function authenticate() {
        $attribute = strpos($this->username, '@') ? 'email' : 'username';
        $user = User::model()->find(array('condition' => $attribute . '=:loginname', 'params' =>
            array(':loginname' => $this->username)));
        if ($user === null) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        else if ($user->Password!=md5($this->password)) {
         $this->errorCode = self::ERROR_PASSWORD_INVALID;
        else {
            $this->_id = $user->Id;
            $this->_LastLoginTime = $user->LastLoginTime;
            $this->username = $user->Email;
            $this->setState('lastLoginTime', $user->LastLoginTime); //set the last login time in varible lastLoginTime from the database. 
            $this->errorCode = self::ERROR_NONE;
    return !$this->errorCode;

Now you can easily print or get your last login time anywhere, eg. -

echo Yii::app()->user->lastLoginTime;

It's show your last time login details (date & time). see in your database, your LastLoginTime table field having different date & time. becuase it's your Current login details (date & time). so if you want to show also your current login details, you can get directory from LastLoginTime fields.

Try this, working great in yii 1.1

Total 2 comments

#18177 report it
Rohit Suthar at 2014/09/22 06:31am
RE #18176

@Rajith Thanks sir :)..

#18176 report it
Rajith R at 2014/09/22 05:53am

Good work, Use with Yii User Module .

Leave a comment

Please to leave your comment.

Write new article