'Session timeout in Yii2

I have used built in yii2 function to set session. I am not able to use built in yii2 login because of some requirement.

So I have set session using below:

Yii::$app->session->set('unique_code', 'xxxx');

and in my config/main.php file

'session' => [
        // this is the name of the session cookie used for login on the frontend
        'name' => 'project-frontend',
        'timeout' => 60*60*24*30,
    ],

But still user is logged out from website after some time.

So how to increase session timeout in this case?



Solution 1:[1]

Problem is in cookies expire time. When it timed out, user is logout. Solution, for changing cookies expire time is in configuration for session component set for cookies lifetime:

    'components' => [
       'session' => [
            'class' => 'yii\web\Session',
            'cookieParams' => ['lifetime' => 7 * 24 *60 * 60]
       ],
   ]

When user login, cookies expire time in current example is after week.

Solution 2:[2]

I will suggest you that if you want to destroy particular session only then set two session:

Yii::$app->session->set('unique_code', 'xxxx');
Yii::$app->session->set('code_time', 'xxxx');

Check current time with code_time, once it is over unset both session.

if you want user should logout after certain time with current solution :

'user' => [
        'identityClass' => 'common\models\User',
        'enableAutoLogin' => false,
        'authTimeout' => 3600, // auth expire 
    ],'session' => [
        'class' => 'yii\web\Session',
        'cookieParams' => ['httponly' => true, 'lifetime' => 3600 * 4],
        'timeout' => 3600*4, //session expire
        'useCookies' => true,
    ],

Solution 3:[3]

En Mysql

CREATE TABLE YiiSession
(
    id CHAR(40) NOT NULL PRIMARY KEY,
    expire INTEGER(11) NOT NULL,
    data BLOB
);

luego en web/config.php

'components' => [
    'session' => [
        'timeout' => 1440, //acá colocas el tiempo en segundos
        'class' => 'yii\web\DbSession',
        'sessionTable' => 'YiiSession',
    ],
    'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => false,
    ],
],

Lo puedes encontrar acá: http://www.bsourcecode.com/yiiframework2/session-handling-in-yii-framework-2-0/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 uldis
Solution 2 Deep Swaroop Sachan
Solution 3 Ricardo Cruz