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.

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...

Popular