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
// close a session
// destroys all data registered to a session.

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');
$session['user_id'] = '1234';
$_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');
$user_id = $session['user_id'];
$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;

Check Session Variable Available Or Not

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

List All Session Variable

foreach ($session as $session_name => $session_value)
	echo $session_name.' - '.$session_value;
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';

$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');

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

Session Timeout


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.


'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:

    expire INTEGER(11) NOT NULL,
    data BLOB

'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,

Leave a Reply

Your email address will not be published. Required fields are marked *