How to increase the session lifetime in Symfony2?

后端 未结 2 456
南旧
南旧 2021-02-06 11:06

I have a login with a remember checkbox. I\'m tring to set lifetime of session to 1 year if the remember checkbox is checked, but no matter what I tried, it doesn\'t work... Sym

相关标签:
2条回答
  • 2021-02-06 11:43

    It should be done in security.yml configuration file:

    secured_area:
        pattern:  ^/yourpattern
        remember_me:
            key:      "%secret%"
            lifetime: 31536000 # 365 days in seconds
            path:     /yourpath
            domain:   .yourdomain.com
    

    You can find related documentation here.

    0 讨论(0)
  • 2021-02-06 12:06

    Normal session lifetime can be managed, according to the documentation, via config.yml:

    framework:
        session:
            cookie_lifetime: 3600
    

    To set the lifetime to a year: 3600*24*365 = 86400*365 = 31536000. Easy :).

    This sets the session cookie lifetime to 1 hour. There are tons of other things you can configure, but that's why I included a link to the documentation.
    If you insist on doing this manually, in a specific case/controller, then pass the options array to the controller. Perhaps that'll work instead of using the setOptions method: If your php.ini contains:

    session.auto_start = 1
    

    Then creating the NativeSessionStorage instance will automatically, and immediately create the session, with the default lifetime. Setting it afterwards will make little or no difference. Check your ini settings, or do:

    $test = new NativeSessionStorage();
    var_dump($test->isStarted())
    

    If it dumps true, try:

    $lifetime = new NativeSessionStorage(
        array(
            'cookie_lifetime' => 31536000
        )
    );
    

    Everything on sessions in Symfony2 can be found here.

    If you are using Symfony2.4, there is a special section in the docs that deals with remember-me functionality, as Jakub Polák pointed out. The essence of it is that the checkbox has to be called _remember_me, that the config.yml has to define a %secret% value, and that you add (a tailored) version of this to your security.yml file:

    firewalls:
        main:
            remember_me:
                key:      "%secret%"
                lifetime: 31536000
                path:     /
                domain:   ~ # Defaults to the current domain from $_SERVER
    

    But the documentation explains this all, but you'll have to "cruise" the manual a bit. For example, if you want to specify different remember-me behaviour for specific sections, change the main in the yml snippet above, and add a pattern setting, as explained here.
    You'd probably best scan the entire security section.

    0 讨论(0)
提交回复
热议问题