Strange behavior with sessions

I have a small custom user-level system. There is a "level" integer field in my user database table and a custom component checks if the user has enough level to access a page.

When the user logs in I set a session variable called level with the value from the database. This is done in the findIdentify method from User controller.

The thing is, if I change the level from the database and I refresh the site without loging out nothings happens because the sessions variable hasn’t changed. This is the behavior I expect. I worked with something like this on Yii 1.1. But if I refresh the site again the session variable changes to the new value without. Why?

Looking at the log I see this: 8 13:22:24.125 info yii\web\Session::open Session started

Why is the session starting when I refresh the page 2 times?

EDIT: Session::open happens all the time, not only after the second refresh. But the session variable still changing after the second refresh.

I’ve waited a while between changing the value from the db and refreshing the site to make sure it’s not because I do it quickly.

A weird thing still happening.

I have my session variable set with the user level which is used to check if the user has permission to do a certain task. It works but if I don’t refresh the site for a while, lets say an hour, when I refresh it I get an exception saying that I’m not allowed to do that task.

I thought it could be because the session is ended or something, but it isn’t. If I refresh the site again it works like nothing happened. The session is set to expire after 30 days, so that’s not the problem.

This is really anoying and never happened in Yii 1.1.x.

Any ideas?

If you are using Cookies to store your session data in (and if this is security data, you should NOT normally do that), then the likely problem is that the value is updated internally, your first refresh gets the updated cookie and only on the second refresh is this cookie sent back to the server from the client to work as expected.

Use a proxy to look at the cookie values being returned from the server and if this is the problem, you should be able to work out what step you are missing (most likely writing to the cookie at the wrong point in the page lifecycle)

I can’t actually find the problem. I’m not storing the user level on any cookie, only on session. And Yii, after a while, renews de session and deletes my session variable.

I’ve solved it by adding this to my custom controller, from where any other controller extends.

if (!isset(Yii::$app->session['level'])) {

    Yii::$app->session['level'] = \app\models\User::findOne(Yii::$app->user->id)->level;


If the session is not set I just search perform a query to the database. But as you can see, Yii::$app->user->id exists because I logged in with this user even if the session['level] variable is gone. Is there any way to store a value there like Yii::$app->user->level = ‘whatever’?