Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
500 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...