Session management in Yii2 Framework

A session is a way to store information (in variables) to be used across multiple pages. In PHP you can directly use session $_SESSION it is global function of PHP.Now i want to show you how to use session in yii2 framework.yii\web\Session instance is used to access the session application component.

Yii2 Session

use  yii\web\Session;

$sessionObj = Yii::$app->session;
// check if a session is already opened
if ($sessionObj->isActive) ...
// opening a session
// closing a session
// destroys all data registered to a session.

How to set Session:
$sessionObj = Yii::$app->session;
$sessionObj->set('website', '');
$sessionObj['website'] = '';
$_SESSION['website'] = '';

How to get Session :
$sessionObj = Yii::$app->session;
$website = $sessionObj->get('website'); //
$website = $session['website']; //

How to remove session variable:
$sessionObj = Yii::$app->session;
unset($_SESSION['website']); // in php

How to check session variable is set:
$sessionObj = Yii::$app->session;
if ($sessionObj->has('website')) 
if (isset($sessionObj['website']))
if (isset($_SESSION['website'])) 

I hope you like this article please comment and share.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...