How to set expiration time to session in the contr

2019-04-17 08:17发布

问题:

I need to set a session with expiration time of 5min in controller. How do i do it? I need something like:

$this->container->get('session')->set('mysession', 'value', 'expiration');

in symfony2 way?

Thanks!

回答1:

This feature is added recently. You can update to this commit or patch. From the code it seems you can set expiry time by following way,

$this->container->get('session')->getMetadataBag()->stampNew(300);


回答2:

Assuming your session is already created, you can achive your goal with:

$this->container->get('session')->migrate($destroy = false, $lifetime = null);

$destroy: Whether to delete the old session or leave it to garbage collection.

$lifetime: Sets the cookie lifetime for the session cookie. A null value will leave the system settings unchanged, 0 sets the cookie to expire with browser session. Time is in seconds, and is not a Unix timestamp.



回答3:

To control the time of the active session (and idle time too) you have to do it in the controller this way (extract from: session configuration in the official doc):

$session->start();
if (time() - $session->getMetadataBag()->getCreated() > $maxTime) {
  $session->invalidate();
  throw new SessionExpired(); // redirect to expired session page
}

When time reaches your $maxTime session is "closed". You can put this code in the backend of your app as a function to call from the different methods to control the time.