Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting online users: PHP

Tags:

php

I am trying to make a thing where it says "X number of users are currently viewing this page" via PHP. How would I do this? Thank you.

like image 770
foob Avatar asked Oct 15 '25 04:10

foob


2 Answers

There's no concept of "currently viewing" on the web, because everything happens as non-persistent connections. The closest you can get is "X users viewed this page during the last N seconds" (and if you choose a value of N that's small enough, you could say that it's pretty much equivalent).

Then, to have user A view data based on user B's actions, in PHP, you need to have some persistent storage, usually as a database like MySQL (but memcached or xcache could work as well, if you don't really worry about losing the data if the server crashes).

Simply write items such as "user X viewed page Y at time Z" to your persistent storage, and when page Y is displayed, query the storage for all views of page Y in the last N seconds, and count the number of different users.

In SQL:

INSERT INTO visits (user, page, time) VALUES (?,?,NOW())

SELECT COUNT(DISTINCT user) FROM visits 
WHERE page = ? AND time < NOW() - INTERVAL 10 SECONDS

You could have the user tell the server "I'm still viewing" by submitting an AJAX request regularly (or having a small iframe on your page that reloads itself every few seconds without JavaScript).

like image 149
Victor Nicollet Avatar answered Oct 16 '25 22:10

Victor Nicollet


  1. Create a database table that stores:
    • A hash of user IP and Useragent combination
    • Timestamp
  2. Upon each pageload, store hash of user IP and Useragent combination along with current timestamp into database
  3. Query database for number of unique entries that have timestamp that falls into NOW() - X minutes range
  4. Display approximate number of active users

Expand on the basic idea by

  1. Having an interval spawned AJAX call to a script that updates db to account for users staying on a page for longer than X minutes
like image 29
code_burgar Avatar answered Oct 16 '25 22:10

code_burgar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!