Zend Framework 2 session life time

2019-05-02 11:25发布

问题:

I am trying to set the max life time of a session with the \Zend\Session\Container. To test it I put it to 1 sec.

Now I looked at the docs

So i did

$config = new StandardConfig();
$config->setOptions(array(
    'remember_me_seconds' => 1,
));
$manager = new SessionManager($config);
$session = new Container('user', $manager);

But no success. Then I started googling and found this answer

So I made the config to

return array(
    'session' => array(
        'remember_me_seconds' => 2419200,
        'use_cookies' => true,
        'cookie_httponly' => true,
    ),
);

(the config worked and was loaded into the manager) but again no success

So I continued searching and found this answer

But again no success.

So after all the searching I couldn't get it working, so now I hope some one else got it working and can help me.

回答1:

Well I finaly found out what the issue was.

The problem was that I used

$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(array(
    'use_cookies' => true,
    'cookie_httponly' => true,
    'gc_maxlifetime' => $config['authTimeout'],
));
$manager = new SessionManager($sessionConfig);

This "worked" the only issue was that there was set a cookie with the lifetime session. This ment different things in browsers. Ie in chrome it is destroyed if you close the tab, so no matter how high the gc_maxlifetime it would not work.

So an easy fix would be the following

$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(array(
    'use_cookies' => true,
    'cookie_httponly' => true,
    'gc_maxlifetime' => $config['authTimeout'],
    'cookie_lifetime' => $config['authTimeout'],
));
$manager = new SessionManager($sessionConfig);

Hope it would help some one in the futue

$config['authTimeout'] is a positive integer value



回答2:

$config = new StandardConfig();
$config->setOptions(array(
    'cookie_lifetime' => '2419200',
    'gc_maxlifetime' => '2419200'
));

Change the value of 2419200 to how many seconds you actually want.



回答3:

In application global.php or you can do it in module config:

 'session_config' => array(
    'name' => 'your session name',
    'remember_me_seconds' => 60 * 60 * 24 * 30*3,
    'use_cookies' => true,
    'cookie_httponly' => true,
),

check Zend\Session\Service\SessionConfig.