简体   繁体   中英

How to create lifetime session in yii2

I have started using Yii2 basic and need to store session information. I already know that in Yii2 basic, this should be done using sessions like

$session = Yii::$app->session;
$session->open();
$_SESSION["a_id"] = $id;
$_SESSION["w_auth"] = "true";

The problem with this is that every time the browser is closed my session expire Is there anyway to keep session alive or set session destroy so even I close the browser and open it again. It will not ask me again to put my username or password.I need to do this in the YII2 Basic .

session cookies set expire time after 7 days `

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

`

You need to use cookies for this. Cookies are info kept in your browser. Here is how to do in yii2:

$cookies = Yii::$app->response->cookies;

// add a new cookie to the response to be sent
$cookies->add(new \yii\web\Cookie([
            'name' => 'a_id',
            'value' => $id,
]));

Add the above cookie when you login and then use it this way in your actions:

$cookies = Yii::$app->response->cookies;

$a_id = $cookies->getValue('a_id');

if($a_id !== null) {
    // user is logged in
}

Note: What is kept in the cookie of your browser is not your actual info, but the session id and this is sent when you reopen your browser and restores your session by this id. Your actual info is kept in your session(in the server). This how yii 2 cookies work.

References

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM