Session Handling In Yii Framework 2.0

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