Yii Framework 2 : Session Handling

A session is a way to store information (in variables) to be used across multiple pages for individual users request. In plain PHP, we can access the session through the global variables $_SESSION.
Now we will see 'How to handle session in yii2'.

Opening and Closing Sessions

'yii\web\Session' instance is used to access the session application component.


use  yii\web\Session;

$session = Yii::$app->session;
// check if a session is already open
if ($session->isActive) ...
// open a session
$session->open();
// close a session
$session->close();
// destroys all data registered to a session.
$session->destroy();

Note: We can use open and close multiple time.

Set Session Variable

Store the value in session variable of yii2.


$session = Yii::$app->session;
$session->set('user_id', '1234');
//OR
$session['user_id'] = '1234';
//OR
$_SESSION['user_id'] = '1234';
    

Get Session Variable

Using below code, we can get the data from the session variable.


$session = Yii::$app->session;
$user_id = $session->get('user_id');
//OR
$user_id = $session['user_id'];
//OR
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
    

Remove Session Variable

To remove the session variable use the below code


$session = Yii::$app->session;
$session->remove('user_id');
//OR
unset($session['user_id']);
//OR
unset($_SESSION['user_id']);
    

Check Session Variable Available Or Not


if ($session->has('user_id')) ...
//OR
if (isset($session['user_id'])) ...
//OR
if (isset($_SESSION['user_id'])) ...
    

List All Session Variable


foreach ($session as $session_name => $session_value)
	echo $session_name.' - '.$session_value;
//OR
foreach ($_SESSION as $session_name => $session_value)
	echo $session_name.' - '.$session_value;
    

Arrays Of Session


$session = Yii::$app->session;
$session['user'] = [
    'id' => 1,
    'username' => 'yiiuser',
];
echo $session['user']['id'];
echo $session['user']['username'];

$session['user.id'] = 1;
$session['user.username'] = 'yiiuser';
    
WILL NOT WORK

$session['user']['id'] = 1;
$session['user']['username'] = 'yiiuser';
    

Flash Data Using Session

Flash data is most commonly used to implement messages that should only be displayed to end users once and will be automatically deleted afterwards.


$session = Yii::$app->session;
//assign the message for flash variable
$session->setFlash('userinsert', 'You have successfully registered.');
// check the availability
$result = $session->hasFlash('userinsert');
// get and display the message
echo $session->getFlash('userinsert');
    
Set Multiple Flash Messages in Single Name

setFlash() function will overwrite existing data from you flash list by name.

If you need to add more messages in single flash name, you can use addFlash() instead of setFlash(). Using addFlash() you can append new messages with existing flash data with same name.


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

// add a multiple messages using addFlash() under the name of "notification"
$session->addFlash('notification', 'You have completed SESSION flash concept.');
$session->addFlash('notification', 'Next you can continue to COOKIE concept.');
$session->addFlash('notification', 'You are going next level.');

// Request #2
// $notification is an array of the flash messages under the name of "notification"
$notification = $session->getFlash('notification');
Output

Array
(
    [0] => You have completed SESSION flash concept.
    [1] => Next you can continue to COOKIE concept.
    [2] => You are going next level.
)

Session Timeout

Note:

The number of seconds after which data will be seen as 'garbage' and cleaned up. The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).

Session logout/timeout is necessary for all application If user is inactive. To enable session timeout, you need to update your components configuration file.

config/web.php

'components' => [
    'session' => [
        'timeout' => 60*60*24*14, // 2 weeks, 3600 - 1 hour, Default 1440
    ],
    'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => false,
    ],
],

Database Session

If you need to use database session, you may require additional driver class (DbSession) for session. You can setup db based session based on below settings. Once you logged-in, the session data will be stored in database.

MySQL DB Session

Session Table:


CREATE TABLE YiiSession
(
    id CHAR(40) NOT NULL PRIMARY KEY,
    expire INTEGER(11) NOT NULL,
    data BLOB
);
config/web.php

'components' => [
    'session' => [
        'timeout' => 1440
		'class' => 'yii\web\DbSession',
		'sessionTable' => 'YiiSession',
    ],
    'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => false,
    ],
],

Redis DB Session

Note: You can add redis package using composer.


php composer.phar require --prefer-dist yiisoft/yii2-redis

Using `redis` component, you can add session data into redis database. To use the redis as application session, you need to configure below settings.


'components' => [
	'session' => [
		'class' => 'yii\redis\Session',
		'redis' => [
			'hostname' => 'localhost',
			'port' => xxxx,
			'database' => 0,
		]
	],
],

  • Saeed Gholizadeh

    Hi,
    I have a problem with getFlash() in yii2

    When use var_dump($_SESSION); I get this result:

    array (size=5)
    ‘__flash’ =>
    array (size=1)
    ‘message’ => int 1
    ‘__returnUrl’ => string ‘/appraisal/form/index?year=2015’ (length=31)
    ‘user.fullname’ => string ‘Saeed Gholizadeh’ (length=16)
    ‘__id’ => int 1
    ‘message’ =>
    array (size=3)
    ‘type’ => string ‘success’ (length=7)
    ‘message’ => string ‘Your Appraisal Saved Successfully.’ (length=34)
    ‘title’ => string ‘Appraisal Saved’ (length=15)

    but when I use
    var_dump(Yii::$app->session->getFlash(‘message’));
    var_dump($_SESSION);

    I get This:

    null

    array (size=4)
    ‘__flash’ =>
    array (size=0)
    empty
    ‘__returnUrl’ => string ‘/appraisal/form/index?year=2015’ (length=31)
    ‘user.fullname’ => string ‘Saeed Gholizadeh’ (length=16)
    ‘__id’ => int 1

    why it gives me null instead of message? it makes it null and removes it from session without giving back the message

  • Higinio Fuentes

    A huge work you have done here http://www.bsourcecode.com/yiiframework2 !!!
    Better than the regular documentation!!!
    Thanks a million for that!