problem with users online script

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Getran
Forum Commoner
Posts: 59
Joined: Wed Aug 11, 2004 7:58 am
Location: UK
Contact:

problem with users online script

Post by Getran »

On my site i made a 'users online' page/system. When a user logs in, it updates a row in my db (adds 1 to the amount) and when they logout it decreases it by one. Simple. But if a user closes the page and ends the session, the amount isn't decreased so is therefore an invalid number...

Can anybody tell me how to make the amount of users online decrease if they close the page ?
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Post by evilmonkey »

I'm not sure if this will work, but you can look into [php_man]register_shutdown_function[/php_man] to execute an SQL query when the session is destoyed. I know it will work for an object, I'm not so sure if this is helpful if you're on the procedural side of things. Nor do I know how this function works. :P

Good luck!
qads
DevNet Resident
Posts: 1199
Joined: Tue Apr 23, 2002 10:02 am
Location: Brisbane

Post by qads »

you could insert a new user as row witha timestamp, when checking for number of users, also put in a delete query which deletes rows older then 3 or mins. something like this would work...

Code: Select all

<?php
//insert user
mysql_query("INSERT INTO users VALUES(".time().")");

//show number of users and delete old rows...
$old = time() - 180//3 mins in secs
mysql_query("delete from users where time <= $old");
$users = mysql_num_rows(mysql_query("select * from users"));
echo $users;
?>
User avatar
Buddha443556
Forum Regular
Posts: 873
Joined: Fri Mar 19, 2004 1:51 pm

Post by Buddha443556 »

There are a number of PHP scripts like Qads described at http://www.hotscripts.com (under Counters>Real Time I think). The method Qads described seems to be the norm.

Just to stay on topic. How about calling a Javascript on unload - client side. Risky in itself and subject to Javascript being enabled.
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Post by d3ad1ysp0rk »

But also make sure your pages have something check the table to see if a row already exists, and if so update the timestamp, else add a new row. That way, if someone spends over 3 minutes reading a topic, then going to another forum, they'll still be in the users logged in script.
Post Reply