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
$sessionObj->open();
// closing a session
$sessionObj->close();
// destroys all data registered to a session.
$sessionObj->destroy();

How to set Session:
$sessionObj = Yii::$app->session;
$sessionObj->set('website', 'www.wantcode.in');
//OR
$sessionObj['website'] = 'www.wantcode.in';
//OR
$_SESSION['website'] = 'www.wantcode.in';

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

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

How to check session variable is set:
$sessionObj = Yii::$app->session;
if ($sessionObj->has('website')) 
//OR
if (isset($sessionObj['website']))
//OR
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