Adjust your login_tracking table to include:
- session_id (varchar 100)
- user_id
- time (updates every 10 minutes for as long as there is activity)
- start (datetime, when they first login)
- end (datetime, when the session is killed either by closed browser or
logout)
Code:
$date = date('Y-m-d H:i:s');
$time=time();
$time_check=$time-600; // user will be marked online if they have any activity for 10 minutes
$session=session_id();
// check if the user is currently listed as online in the database
$getactiveession = mysql_query("SELECT * FROM login_tracking WHERE session = '$session' AND end IS NULL");
$active_session = mysql_num_rows($getactivesession);
// if they are not listed as online, insert a row for them
if($active_session == "0"){
$make_active = mysql_query("INSERT INTO login_tracking (session, user_id, time, start) VALUES('$session', '$user', '$time', '$date')");
}
else {
// UPDATE user's current time if they are already currently logged in
$update_session = mysql_query("UPDATE login_tracking SET time = '$time', user_id = '$user' WHERE session = '$session'");
}
// get total users online
$gettotalonline = mysql_query("SELECT * FROM login_tracking");
$total_online = mysql_num_rows($gettotalonline);
// if over 10 minutes and no new activity (time column has not been updated), update end session time
$end_session_time = mysql_query("UPDATE login_tracking SET end = '$date' WHERE time<$time_check");
With this you can display a list of all online users as well with links to their profile, avatars, etc.
only thing I can think of is when inserting the new row for a new logged in user, you might have to do "WHERE end = '0000-00-00 00:00:00" instead of "WHERE end IS NULL", not sure if you can do a IS NULL on a datetime.
Response to your Comment #1
I have a SIMILAR thing as a function on my site which is located on every page therefor no matter what page my user is browsing they will be considered logged in. So it's easy to implement everywhere.
However, you will probably need to set part of it up as a cronjob to run every minute or 10 minutes to check for records over 10 minutes. I say this because...if a user closes their browser but does not log out, it will not update their record in the database until another person (logged in or guest) accesses the page in which the above code is being run on. If you have a cronjob running it then there would be no problem. (this also addresses your comment about the end session time getting executed, my site doesn't require that so happy you brought up the point, therefore a cronjob for you would be a must I think).
As for redirecting them to the logout page, I'm not sure how that would work in this case seeing as their page is not being refreshed. That would probably need to be ajax or something.