How to Implement Session Timeout?

I want to implement a session timeout scheme in a Yii application, such that after a user has logged in, if there is no activity for a specified length of time, when the user tries to access any page that is available only to logged-in users, Yii detects it and displays a suitable message (e.g. The Session has expired) and redirects the user to the login page and after successful login, the ‘original requested page’ is displayed. Meanwhile any page not requiring login will continue to be available. Is this functionality built-in in Yii, and if yes, how do I use it? If no, any suggestions how to implement it?

Thanks for your help.

You can add in the table user a field like "last activity".

You can use something like that:


if ((strtotime('now') - $user->lastActivity) > $maxIdleTime)







   $user->lastActivity= strtotime('now');



You can place this code in beforeAction or any function that is called before the action of the controller.

You can create a master class for your controller and extend it, or you can use behaviour for attach this code to your contollers.

Thank you so much for your suggestions. I am thinking about extending the Controller class and including the code you have suggested in the beforeActiom() function. So far so good. However, there are two issues:

  1. No user may not be logged in. (I can check for that condition in beforeAction())

  2. Certain actions, e.g. actionIndex or actionView on certain controllers are available to everyone (logged-in as well as not logged in users) and I don’t want to display “sessionExpiried” page for these actions, regardless whether the session has expired or not, including for logged-in users. Of course, it will be too cumbersome to put the session expired checking code in individual actions in all controller. Any suggestions?

I guess you use RBAC for check who has the right for do what.

You can use a bizrule on the role you want to avoid to be idle too much. Usually biz rule are used for check additional condition, and this is absolutely this case.

You can write this code in an extension of CWebUser that you will use instead of the base class, and like bizrule yuo can write something like


I never tried this approach, let me know if it works.

I am also thinking on similar lines, i.e. if I can find out Idle time from the user object or I can handle it through a session variable. I believe, whenever any page is accessed, it passes through the accessRules() function of the corresponding controller. So accessRules() of the Controller or some function before/after this may be the appropriate place to determine idle time. Any thoughts? By the way, which class/object calls Controller’s accessRules() function?