Skip to main content

SilverStripe content management system is near version 3, the latest stable version that will be released in several months, and we continue to provide SilverStripe tips and tricks to you.

This article shows how to logout inactive user after some period of time.

- Advertisement -
- Advertisement -

First, you need to make changes in the init() function in the Page.php file, class Page_Controller:

...
function init() { 
  parent:: init();
   
  // Call function to logout inactive user
  self::logoutInactiveUser(); 
}
...

After this modification, create the function that will actually logout inactive user after some period of inactivity:

/**
* The function will logout a user after certain amount of time
*
*/
function logoutInactiveUser() { 
  // Set inactivity to half an hour (converted to seconds)
  $inactivityLimit = 30 * 60;
   
  // Get value from session
  $sessionStart = Session::get('session_start_time'); 
  if (isset($sessionStart)) {
    $elapsed_time = time() - Session::get('session_start_time');
    // If elapsed time is greater or equal to inactivity period, logout user
    if ($elapsed_time >= $inactivityLimit) { 
      $member = Member::currentUser(); 
      if($member) {
        // Logout member
        $member->logOut();
      }
      // Clear session
      Session::clear_all();
      // Redirect user to the login screen
      Director::redirect(Director::baseURL() . 'Security/login'); 
    } 
  }
   
  // Set new value
  Session::set('session_start_time', time()); 
}

Now, all users that were inactive in the last 30 minutes will be automatically logout from SilverStripe and redirected to the login page.

- Advertisement -