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');
$user->saveAttributes(array('LastLoginTime'));
return true;
} else {
return false;
}
}
}
In Your config main.php
Need to set WebUser class in user array -
'class'=>'WebUser'
eg. -
// application components
'components'=>array(
'user'=>array(
'class'=>'WebUser', //Adding WebUser class
'allowAutoLogin'=>true,
'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
Cool
Good work, Use with Yii User Module .
RE #18176
@Rajith Thanks sir :)..
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.