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.
-
How are the users logged in the chat room? – chris85 Feb 05 '17 at 14:19
-
For example by counting unique IP adresses or counting active sessions – Nils Feb 05 '17 at 14:19
-
@Nils IPs aren't people and can't reliably count/identify people. – chris85 Feb 05 '17 at 14:19
-
User can join room with or without registation. – Aram810 Feb 05 '17 at 14:20
-
So how are users in a room managed? – chris85 Feb 05 '17 at 14:21
3 Answers
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.

- 1,155
- 9
- 12
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.

- 1
- 1

- 776
- 5
- 13
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

- 1,763
- 1
- 25
- 41