I am a beginner learning to use this wounderful PHP framework. I wanted to implement session timeout in my application. I did a lot of search but could not find steps simple enough for me to understand. Well, I managed to implement Session Timeout in my application. I decided to put it here, just in case someone else may find it useful. And, experts may comment if there is any flaw in this implementation.
First I created a session timeout parameter that holds the timeout value. (Store it in proteced\config\main.php or your parameters files, e.g. protected\config\params.php)
'sessionTimeoutSeconds'=>300, //timeout value in seconds
);
Next, in the authenticate() function of protected\components\UserIdentity.php, use the following command to store the time when the tiemout should happen in a user session variable after successful login.
// Define sessiotimeout value
yii::app()->user->setState('userSessionTimeout', time()+Yii::app()->params['sessionTimeoutSeconds'] );
Next, in the protected\components\Controller.php, add the following function:
public function beforeAction(){
// Check only when the user is logged in
if ( !Yii::app()->user->isGuest) {
if ( yii::app()->user->getState('userSessionTimeout') < time() ) {
// timeout
Yii::app()->user->logout();
$this->redirect(array('/site/SessionTimeout')); //
} else {
yii::app()->user->setState('userSessionTimeout', time() + Yii::app()->params['sessionTimeoutSeconds']) ;
return true;
}
} else {
return true;
}
}
The beforeAction() code runs before any action runs. Notice that the code checks if time stored in userSessionTimeout has passed only for logged-in users. (Thus if the user is not logged in, all pages that do not require login will continue to work.). In case of sessiontimeout, it logs out the user and calls the SessionTimeout action in the Site controller. So, add the following code in the SiteController.
public function actionSessionTimeout()
{
$this->render('sessiontimeout');
}
actionSessionTimeout() just renders views\site\sessiontimeout.php view file where you can display a suitable message. Here is a simple views\site\sessiontimeout.php file.
<?php
$this->pageTitle=Yii::app()->name . ' - Session Timeout';
?>
<h1>Session timeout</h1>
<div class="error">
<?php echo CHtml::encode('Session timed out. Please login again to continue.'); ?>
</div>
Note: The above scheme does not take care of Ajax callbacks.