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.