2

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.

Ninja Turtle
  • 1,293
  • 2
  • 24
  • 50
  • 1
    Possible duplicate of [How to see if a user is online in a website with php and mysql driven databases?](http://stackoverflow.com/questions/8026263/how-to-see-if-a-user-is-online-in-a-website-with-php-and-mysql-driven-databases) – Alexander O'Mara Jul 17 '16 at 05:56
  • Looks like here is your solution: https://github.com/samdark/yii2-cookbook/issues/92 – oakymax Jul 17 '16 at 10:41

1 Answers1

6

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.

oakymax
  • 1,454
  • 1
  • 14
  • 21