问题
User's in Yii appear to be logged out automatically if they close their browser or are idle for about a day (maybe less, I'm not sure). Is it possible to not log them out ever (or at least for a long time for month or year). Not sure if the Session parameters or Cookie parameters need to change.
I've tried changing the parameters.
'components' => [
'session'=>[
'class' => 'yii\web\Session',
'cookieParams' => ['httponly' => true, 'lifetime' => 3600 * 4* 365],
'timeout' => 3600*4 *365,
'useCookies' => true
],
]
I've tried session php ini parameters:
session_set_cookie_params(0);
ini_set('session.gc_maxlifetime', 0);
And I've tried setting the login parameters
Yii::$app->user->login($user, 31536000);
回答1:
The options you used it should work without timeout
and useCookies
options, I used it in my last project where the session needed to last for a week minimum, open storage tab in the Mozilla dev bar and click on cookies on the left you will see the cookies section with the cookies registered for your site, in my case it is http://www.kp2.local
if you use the 'lifetime' => 7 * 24 * 60 * 60,
it should show the cookie with an expiry date 1 week later i.e Wed, 23 Jan 2019
like below
and if you comment out the code and then log out, and log in again it should show you the expiry time on Session
like
You just need to use the following settings in the config
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
'cookieParams' => [
'httpOnly' => true,
'lifetime' => 7 * 24 * 60 * 60
],
],
If it still doesn't work, log out of the system try removing all cookies once by selecting Delete all
option like in the image below.
and it will work.
Note: You should change the 7
in 'lifetime' => 7 * 24 * 60 * 60,
to the number of days you want to keep the session
回答2:
Keeping session for such long time may be a bad idea - inactive sessions data will consume your server resources and may slow down some operations. Yii has dedicated feature for such cases - you may set $enableAutoLogin to true
:
'user' => [
'enableAutoLogin' => true,
// ...
],
And on login()
call set timeout for identity cookie:
Yii::$app->user->login($user, 31536000);
It will set special cookie (valid for a year) with identity info, which will autologin user after his session expires. In this way you don't need to keep session data on your server for a year, but from user perspective it looks like he is always login (even if in the background a new session is created).
来源:https://stackoverflow.com/questions/54210708/yii2-never-logout-idle-or-away-user