Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

script to tell me who, and how many users, are online

Tags:

sql

php

mysql

In my research to find a way to make PHP tell me how many people are 'online' on my site I've discovered that there are ways to 'estimate' this.

I've chosen to log everything that happens on the site, also for error-management sake, but now i'm stuck at writing my SQL query.

Basicly I have a database with 'IP', 'userid' and 'datetime' and I figured that a query like this would do the trick:

SELECT distinct(IP), datetime 
FROM `bigBrother` 
WHERE datetime BETWEEN DATE_SUB(NOW(), INTERVAL 3 MINUTE) AND NOW()

The problem is that my site is mostly viewed and used by students on the school network, and well... they all have the same IP.

So the question is, am I doing this right, and can I select two distinct rows from my database, so that I can sort out the registered users (who will have a 'userid' - others will have userid = 0)?

like image 977
Jasper Avatar asked Feb 20 '09 09:02

Jasper


3 Answers

Just use the session id instead of the IP.

like image 76
troelskn Avatar answered Nov 10 '22 15:11

troelskn


Use cookies instead of IP addresses.

PHP makes it very easy with it’s session mechanism. On each you first do a session_start() and then you use the value returned by session_id() as a identifier of the visitor that you can put in your database.

like image 31
kmkaplan Avatar answered Nov 10 '22 16:11

kmkaplan


I created a system for a school site that asked for this feature as well and here's how i did it.

I had a table of users, in that table there was a field called "online_time"

On every page a function was called if the user was logged in that updated the "online_time" to the current time of that user. (unixtime)

Then i had an "Who is online" function that looked at the "online_time" and displayed all the users with the online time of the last 5 minutes.

EDIT to the comment:

You could make the same function save the session id in another table and the time it was saved. The session id is unique to that user browsing, so you could get the number of session id's active within the last 5 minutes.

session_id()
like image 43
Ólafur Waage Avatar answered Nov 10 '22 15:11

Ólafur Waage