Thursday, 6 October 2016

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.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts