Skip to content

How to configure a session timeout

Adam Lundrigan edited this page Jan 14, 2015 · 3 revisions

Task

Automatically terminate a user's session after a specific period of inactivity.

Solution

  1. Add session factories and configuration to your application via a module config or config/autoload file:

    return [
        'service_manager' => [
            'factories' => [
                // Configures the default SessionManager instance
                'Zend\Session\ManagerInterface' => 'Zend\Session\Service\SessionManagerFactory',
                // Provides session configuration to SessionManagerFactory
                'Zend\Session\Config\ConfigInterface' => 'Zend\Session\Service\SessionConfigFactory',
            ],
        ],
        'session_config' => [
            // Set the session and cookie expiries to 15 minutes
            'cache_expire' => 900,
            'cookie_lifetime' => 900,
        ],
    ];
    
  2. In Application\Module::onBootstrap, pull an instance of the SessionManager. This will inject the properly-configured SessionManager instance as the default for all new session containers.

    public function onBootstrap(MvcEvent $e)
    {
        $manager = $e->getApplication()->getServiceManager()->get('Zend\Session\ManagerInterface');
    }