Vinit Singh Vinit Singh - 3 months ago 107
PHP Question

How to get list of all logged in users in Yii2?

I want to show list of all logged in users to admin in my yii2 application. right now i am using a boolean variable 'is_login' which is set when user logs in and unset when user logs out. Now the problem is if user close the browser without logging out it will display in logged in users. how to display only active users.

I don't thinks storing user activity on every click or whenever he/she do something on website is the right way, that makes website too much cumbersome?
I am asking about if there is any standard method or way is available for it in Yii2.

Answer

The right way here is to work directly with a list of active sessions. By default sessions are stored in filesystem (each in own file) and it can be inconvenient to work with them. It will be much easier for you, if you'll use yii\web\DbSession storage instead of default yii\web\Session. Then you will be able to query all sessions right from database.

Here is samdark's recommendation: https://github.com/samdark/yii2-cookbook/issues/92

Could be solved by using DB sessions and writing additional info into the table:

'session' => [
    'class' => 'yii\web\DbSession',
    'writeCallback' => function ($session) {
        return [
           'user_id' => Yii::$app->user->id,
           'last_write' => time(),
       ];
    },
],

Then it's easy to work with it via SQL:

-- Get all users active in recent hour
SELECT user_id FROM session WHERE last_write - 3600 < :now;

P.S. Prior to use this config you should execute a migration to add session table to your db and add fields user_id and last_write.

Default migrations are under this path: vendor/yiisoft/yii2/web/migrations.

Or just execute something like this (should be adopted to your case):

CREATE TABLE session
(
    id CHAR(40) NOT NULL PRIMARY KEY,
    expire INTEGER,
    data BLOB,
    user_id INTEGER,
    last_write TIMESTAMP
)

To learn more about sessions in Yii2 visit this section of Yii2 guide.