sai
sai

Reputation: 43

How to retrieve the session values in Yii 2

I am facing the problem with Yii 2 session when I add the products to the cart session and fetch session cart values.

session_start();
print_r($_SESSION);
exit;

I got this line.

Array ( [__flash] => Array ( ) [__id] => 65 )

Also while trying Yii 2 way:

$session = Yii::$app->session;
print_r($session);
exit;

I am getting this value:

yii\web\Session Object ( 
    [flashParam] => __flash 
    [handler] => [_cookieParams:yii\web\Session:private] => Array ( [httponly] => 1 ) 
    [_hasSessionId:yii\web\Session:private] => 1   
    [_events:yii\base\Component:private] => Array ( ) 
    [_behaviors:yii\base\Component:private] =>

How to get the session data with keys and values in Yii 2?

Upvotes: 2

Views: 12547

Answers (6)

buzz8year
buzz8year

Reputation: 416

You need to process Yii::$app->session object in for/foreach loop, like so:

foreach (Yii::$app->session as $key => $value) { 
        var_dump($value); 
}

Upvotes: 0

Shamsi786
Shamsi786

Reputation: 159

Hi Sai you can set or retrieve the session value in yii2 easily by using the following steps

1) To set session value on var 'userVariable'

Yii::$app->session->set('userVariable','1234');

2) For getting the session value of var 'userVariable'

$userVariable = Yii::$app->session->get('userVariable');

Upvotes: 4

ynz
ynz

Reputation: 856

First, you need to open session

Yii::$app->session->open();

And you can get all session using $_SESSION

var_dump($_SESSION);exit;

May be useful!

Upvotes: 1

jack
jack

Reputation: 843

you can get session ID with

Yii::$app->user->id
//OR
Yii::$app->user->identity->id

and you can set new session with

$session = Yii::$app->session;
$session->set('new-name-session', '1234');

check all session with

var_dump($_SESSION);exit;

Upvotes: 0

Saleem Khan
Saleem Khan

Reputation: 150

You don't need to start session IF you are using YII2 framework. Follow these step: 1. $session = Yii::$app->session; 2. $session->set('key', 'value'); 3. $session->get('key');

Otherwise directly set value

$session['key']=>'value'

Upvotes: 0

Amit Sahu
Amit Sahu

Reputation: 996

you can get session by using $session = Yii::$app->session; hope it will help you :)

Upvotes: 2

Related Questions