0

I have a chat room and I want to show how many people are online exactly in this chat at this moment. User can join room with or without registation.

Aram810
  • 619
  • 7
  • 21

3 Answers3

1

This is strongly dependant on the way you implement the chat room. You could assign a chat-session id and timeout to each visitor, which gets expired over time and removed from a list. This list will contain details on visitors, including the count.

Rilke Petrosky
  • 1,155
  • 9
  • 12
1

Just a quick idea that has come to my mind (can be heavily customized and improved):

1) Call a PHP script periodically (for instance, once per a minute) through an AJAX call with a unique per-user ID. Like this, for example:

var visitorCounter = function() {
    $.get('audience_checker.php', {
      id: get_random_id() // inspiration below 
    });
}

setInterval(visitorCounter, 60000); // it gets called every 60000 ms = 1 minute

Take an inspiration how to build a random ID generation here. Or use the IP address.

2) Now write the PHP script that will store IDs from $_GET super-global variable in a database, with timestamp. If the ID already exists, just update the timestamp.

3) And finally, another script statistics.php can just select those data from the database which are not older than a minute bases on the timestamp.

Community
  • 1
  • 1
Ivan Kvasnica
  • 776
  • 5
  • 13
1

Of course will depend on your chat application logic but that's something I am using to count the users in my application. It is not perfect because you never know about your users if they don't log off. You can add a new table to handle sessions:

`id`, `expire`, `data`, `user_id`, `last_write`

then change the configuration to save the sessions into this table instead of files.

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

then you can check the sessions in the last 5 minutes for instance

Hope it helps

open-ecommerce.org
  • 1,763
  • 1
  • 25
  • 41