Yii2 and sessions

Hi there,

i have a question about sessions in Yii2.

I set a session variable in my code. If i closing the browser tab and then i start a new tab and call my website, is the session variable always set.

How can i delete the session variable when the User is closing his browser tab?

I hope anybody can help me.

Session is set on the server not client. If you want some control on client then use cookies not session. But then you cannot store sensitive information since user can inspect cookie and that user might happen to be malicious!

See: PHP: setcookie - Manual
expires_or_options

The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. One way to set this is by adding the number of seconds before the cookie should expire to the result of calling time(). For instance, time()+60*60*24*30 will set the cookie to expire in 30 days. Another option is to use the mktime() function. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

For Yii2

// get the cookie collection (yii\web\CookieCollection) from the "response" component
$cookies = Yii::$app->response->cookies;

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

Thank you very much. This help me :slightly_smiling_face:

1 Like