I had similar problem on my site also and here's a solution a came up with:
Following script is included on every page necessary.
PHP Code:
//current unix-time
$time_start = time();
//update field 'isonline' in table 'users'
// For database commands I'm using Abstract Pear classes
$update_onstats =
$db_object->query("UPDATE users SET isonline = $time_start WHERE username = '".$_SESSION['username']."'");
After that is quite simple to compare current time with that stored in the database whenever it's necessary. For example I use it like this:
PHP Code:
$log = $db_object->query("SELECT id, username, isonline FROM users ORDER BY ID DESC");
if (DB::isError($log)) {
die($log->getMessage());
}
// current unix-time in which
// we will compare the one stored in the database
$currentT = time();
.
.
.
.
//this loop outputs all users and in the same time substracts
// time stored in database from current time on every row
while ($row = $log->fetchRow(DB_FETCHMODE_OBJECT) ) {
echo '<tr>';
$receiver = $row->username;
$re_id = $row->id;
$subs = $currentT - $row->isonline;
//substract time stored in database from current time
$subs = $currentT - $row->isonline;
// if the result is smaller than 1970 seconds
// td class 'act' in CSS file is chosen which highlights the users
// currently online.
// The ones which are offline are shown differently and are less
// 'visible'
// Loop also creates a link which leads straight to html-form used for
//messaging in which the user who's name was on the link is the receiver.
if ( $subs < 1790){
$tdclass= 'act';
}else { $tdclass = 'defa'; }
print ("<td class=\"" . $tdclass . "\" align=\"left\"> <a href='shal.php?choise=write&check_write=true&receiver=$receiver&re_id=$re_id'>[" . $row->username . "</a> </td>" );
}
The way I use this requires a CSS-file also but I believe it's quite simple to use similar method to output only those users who are currently online.
I use this script on my page in private-messages so that people can see who's online, but can also send messages to those who are not.
The key is to update time in the database on every pageload.
At logout before session_destroy() and unsetting variables I use this:
PHP Code:
$update_onstats = $db_object->query("UPDATE users SET isonline = 0 WHERE username = '".$_SESSION['username']."'");
In result the name of the user which logged out isn't highlighted anymore.
Hope this helps
Bookmarks