How to set expiration time to session in the controller?

痴心易碎 提交于 2019-12-06 15:58:57

问题


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.



来源:https://stackoverflow.com/questions/10330865/how-to-set-expiration-time-to-session-in-the-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!