user5300122
user5300122

Reputation: 143

Yii2 session expires after user is idle for a fixed seconds despite session timeouts being set to at least 1 day

I have already added these codes in my config/web file

 'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => true,
         'enableSession' => true,
        'authTimeout' =>86400,
          'loginUrl' => ['account/login'],

    ],
      'session' => [
                    'timeout' => 86400,
            ],

After session expires I want to automatically logout and redirect to login action.

Upvotes: 2

Views: 5785

Answers (2)

Arie Satriananta
Arie Satriananta

Reputation: 51

Make sure in your php.ini file
config

session.gc_maxlifetime

by default set as :

session.gc_maxlifetime=1440

change it, to :

session.gc_maxlifetime=86400

Upvotes: 2

S.Yadav
S.Yadav

Reputation: 4509

Very first you have to set 'enableAutoLogin' => false, . now add these lines there in your config/web. I have added it in frontend/config/main.php because I am using frontend only.

'components' => [
...
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => false,
            'enableSession' => true,
            'authTimeout' => 1800, //30 minutes
            'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'class' => 'yii\web\Session',
            'name' => 'advanced-frontend',
            'timeout' => 1800,
        ],
...

Now go to yii2/web/User.php and write code for destroy session in logout method before return as guest()-

public function logout($destroySession = true)
    {
        $identity = $this->getIdentity();
        if ($identity !== null && $this->beforeLogout($identity)) {
            ......
            if ($destroySession && $this->enableSession) {
                Yii::$app->getSession()->destroy();
            }
            $this->afterLogout($identity);
        }

        $session = Yii::$app->session;

        $session->remove('other.id');
        $session->remove('other.name');
              // (or) if is optional if above won't works
        unset($_SESSION['class.id']);
        unset($_SESSION['class.name']);
              // (or) if is optional if above won't works
        unset($session['other.id']);
        unset($session['other.name']);

        return $this->getIsGuest();
    }

For me it worked great.

Upvotes: 0

Related Questions