Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I count sessions to determine number of people online?

Tags:

php

mysql

session

I am confused about something. When I try to search how to count online users in PHP, all answers related with MySQL and many different ways.

In my script, any user that submits the login form creates a $_SESSION['$nickname']

So I thought, can I count login sessions with count($_SESSION['$nickname']); and show it in my page?

Or is this totally a wrong logic?

like image 519
Slavez Avatar asked Nov 22 '25 16:11

Slavez


2 Answers

Totally wrong logic. $_SESSION is a per-user thing. One user's session is not shared with any other user's session. Think about it - an online bank written in PHP, all sharing a single $_SESSION - everyone would see everyone's account details.

Assuming you're on the standard PHP file-based sessions, you can count the session files in whatever directory they're stored, e.g.

$users = count(glob(session_save_path() . '/*'));

Note that this just counts session files - it will undoubtedly contain stale/dead sessions that haven't been garbage collected yet. If you want an actual "really is online right now", you'd have to parse each session file and examin its contents.

like image 199
Marc B Avatar answered Nov 25 '25 04:11

Marc B


At first, you have to define what "to be online" means. Should the user have clicked on a link within the last 5 minutes?

I assume that you already have a user table in your database. So the simplest way is to add a new column, e.g. lastAction TIMESTAMP.

And when the user clicks on a link on your page, your script should update this value.

And on your statistics page or whatever, you get the number of online users with that code:

SELECT COUNT(*) FROM users WHERE lastAction > (NOW() - 60*5)
like image 25
ComFreek Avatar answered Nov 25 '25 05:11

ComFreek