Question: How to make Simple Users online script?


( Back )

Answer #1:

1. Add a field to your table that will serve as a flag to tell you if the user is logged in or not. The values could be limited to 0 or 1. 0 being not logged in, 1 being logged in.

2. When a user logs in, update the field you just created (only for that user) to a value of 1.

3. To determine who is currently logged in, query the table to find only records where the login flag field is equal to 1. Something like: SELECT * FROM users WHERE login_flag = 1

4. Do not forget to set the login flag back to 0 when a user logs out or ends their session.

> Edit:
I don't understand. If the network is disconnected then your host cannot connect to a database and they can't login anyways. Therefore, no users would be online because... the network is disconnected.

Answer #2:

You already have your answer. If you have the active, when someone logs on, make it a one, when they log off, make it a zero. Just use a hidden field in the form. Just make sure that if they close the website, that you use JavaScript to call an onclose event to reset.

Each time a user name, icon (avatar) or whatever reference you have to them gets displayed, it just needs to query the active entry.

Answer #3:

Try the heartbeat method!
Every X seconds the client sends a request to the server that says "I'm still here". So you basically check against your list of users and their last heartbeat time, if X amount of time has passed since the last heart beat they are offline.

Each client is going to have to constantly query the server for the most recent messages anyway right?
So you might as well use that request as your heartbeat!

Use the following table to store the last heart beat:
create table LASTREQ (`id` INTEGER PRIMARY KEY, `userid` INTEGER, `lastreq` AS DATETIME);
ON each request, update the last value for the requesting user:
update LASTREQ set `lastreq` = NOW() where `userid` = <user>
Use the following query to get a list of users online:
SELECT * FROM users LEFT JOIN lastreq ON lastreq.userid = users.id && lastreq.lastreq >= NOW()-<x seconds>;

That's all psuedo code, you'll have to come up with valid sql, but its pretty close!

All the best!!!





** Powered by Yahoo Answers