Help with Sessions

I am a new yii user and am trying to play with yii2. I have a site I am working on and while I develop locally, I like to display my session variables on the screen. Normally I would simply start the session on my index.php page and iterate over the $_SESSION array to display each Key=>Val pair.

How do I do this in Yii2? I have in my web.php file…

‘session’ => [

 'name' => 'My Session Name',

 'savePath' => '/path/to/save/SESSIONS',


as I understand it, the session autostarts? So if I wanted to iterate over the Yii::$app->session component, how would I and where do I put the code if I want it to display on every page? I was thinking the output on main.php?

Thanks in advance for input.

You can view session contents in debug toolbar but if you want to access it from code here’s how:

foreach (Yii::$app->session as $name => $value) {

  echo $name . '=' . $value;


Thanks for the reply. I added this code to my main.php in layouts and I get an error “Array to string conversion” error on the line with “echo $name . ‘=’ . $value;” and I don’t know why.

My SiteController -> actionLogin looks like this

public function actionLogin()


        if (!Yii::$app->user->isGuest) {

            return $this->goHome();


        $model = new LoginForm();

        if ($model->load(Yii::$app->request->post()) && $model->login()) {

            // get the users user_id and set some session vars....

            $userID = Yii::$app->user->getId();

            $userInfo = User::findOne($userID)->getAttributes();

            foreach($userInfo as $key=>$val){



            return $this->goBack();

        } else {

            return $this->render('login', [

                'model' => $model,




Hi, on Yii 2.0.45 and PHP 8.1 I’m getting this error when i loop through sessions

During inheritance of Iterator: Uncaught yii\base\ErrorException: Return type of yii\web\SessionIterator::current() should either be compatible with Iterator::current(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in vendor/yiisoft/yii2/web/SessionIterator.php:60

this is my code

        $session = Yii::$app->session;
        foreach ($session as $key => $value) {
                if ($session->has($key)) $session->remove($key); //remove session

Any ideas? Thank you.

It’s already fixed in master so you can try switching to master@dev version for now.

1 Like

thank you!