Session in yii2

import Session Class

use  yii\web\Session;

Create a session

$session = Yii::$app->session;
$session->open(); // open a session
$session->close();  // close a session

Store the value in session variable.

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

$session->set('name', 'stack');
OR
$session['name'] = 'stack';
OR
$_SESSION['name'] = 'stack';

Get the value from the session variable.

$name = $session->get('name');
OR
$name = $session['name'];

Remove the session variable

$session->remove('name');
OR
unset($session['name']);
OR
unset($_SESSION['name']);

$session->destroy(); // destroy all session 

Remove all session variables

$session->removeAll();

Check Session variable

$session->has('name')
OR
isset($session['name'])
//both function return boolean value [true or false]

Session Flash

Set session flash

$session = Yii::$app->session;
$session->setFlash('error', 'Error in login');

Get session flash

echo $session->getFlash('error');

Check session flash

$result = $session->hasFlash('error');

Remove session flash

$session->removeFlash('error');

Remove all session flash variables

$session->removeAllFlashes();

Directly use session variable

Set and get session variable

\Yii::$app->session->set('name','stack');
\Yii::$app->session->get('name');

Session flash

\Yii::$app->getSession()->setFlash('flash_msg','Message');
\Yii::$app->getSession()->getFlash('flash_msg');

if you want to reproduce, please indicate the source:
Session in yii2 - CodeDay