How to prolong the remember_me cookie on each request in Symfony2?

大憨熊 提交于 2019-12-11 05:23:42

问题


I use standard remember_me symfony feature, but it expires every period of time, set in config. E.g. I have lifetime set to 1800. Disregarding of what I do, it logs me off after 0.5 hours after last login. And I want it logs me off only after 0.5 hours of inactivity.

Every request should prolong remember me cookie.

Could this be done with just config or should I mess with kernel events and hack that manually?


回答1:


There is indeed a way to do it only with configuration settings, but only in Symfony 2.1. The way to go is to use the garbage collection of sessions integrated within PHP. Here how you can achieve it.

In your config.yml file, set the variables below:

framework:
  session:
    cookie_lifetime: 86400 # One day, cookie lifetime
    gc_maxlifetime: 1800 # 30 minutes, session lifetime
    gc_probability: 5
    gc_divisor: 100

With this configuration, the cookie sent to the browser will be valid for one full day. However, the session will last 30 minutes. Since sessions are saved on every request, the lifetime will be "restarted" after each request. So, the session will be prolonged on each request.

Then, comes the garbage collection part. And this can be "problematic" depending on how precise you want to be. The properties gc_probability and gc_divisor controls how often garbage collection will run. Those numbers mean that GC will be run with a probability of 5% (5/100, gc_probability/gc_divisor) on each session initialization.

This means that when GC will run, it will remove expired sessions. However, since this is a probabilistic feature, you do not have full control over it. Some sessions could still be accessed after the lifetime you specified, because the GC has not run yet.

If this is a problem for you, then you need a listener on each request and check that the session is still valid. You also need to do this if you want to display a message to the user when is session has expired since there is no session expired event yet.

Do not forget, my answer will be valid only in Symfony 2.1. On 2.0, you will also need a request listener to validate the session lifetime value.

Here some links about session idle times:

  1. A link on the PR that introduces keep alive sessions: PR-2171
  2. Documentation on session: here
  3. PHP site on gc of session: here

Hope this helps you.

Regards, Matt



来源:https://stackoverflow.com/questions/12605681/how-to-prolong-the-remember-me-cookie-on-each-request-in-symfony2

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