How to retrieve the session values in Yii 2

拥有回忆 提交于 2019-12-08 10:42:47

问题


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?


回答1:


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




回答2:


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'




回答3:


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;



回答4:


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!




回答5:


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');


来源:https://stackoverflow.com/questions/41361322/how-to-retrieve-the-session-values-in-yii-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!