tags:

views:

183

answers:

1

Hi, I have this Drupal website and I want to have my own chat (can't use chat module because I have to personalize it). I have to retrieve all the online users but I can't see any variable for that.

I am only able to get the name of the currently logged in user but not the rest of the users logged in.

+4  A: 

You can fetch a list of all logged in users by querying the sessions table. I'm assuming you're using Drupal 6.

<?php
$result = db_query('SELECT uid FROM {sessions} WHERE uid != 0');
$users = array();
while($user = db_fetch_array($result)) {
  $users[] = user_load($user);
}

The query excludes sessions for uid = 0 as these are anonymous users. $users is the array of user objects as described in the Drupal API Docs.

You can optimize this if you already know what part of the user objects you will use (e.g. just the user id and name) by removing the user_load() in while loop and adding to the query a join with the users table, as each user_load() makes one additional query. The following would get you a list of logged in users' id and names:

<?php
$result = db_query('SELECT u.uid, u.name FROM {sessions} s INNER JOIN {users} u ON u.uid = s.uid WHERE s.uid != 0');
$users = array();
while($users[] = db_fetch_array($result));

Since logged in users never time out (you can stay logged in indefinitely), it may be useful to exclude logged in users who haven't accessed the site in a while (i.e. maybe an hour of inactivity):

$timestamp = time - 3600; // 3600s is one hour.
$result = db_query('SELECT uid FROM {sessions} WHERE uid != 0 AND timestamp >= %d', $timestamp);

You might also want to limit how many users to return. For example, maybe you want to grab - at most - the last 10 logged in users who accessed the site:

$limit = 10; // Limit to the last 10 users.
$result = db_query_range('SELECT uid FROM {sessions} WHERE uid != 0 ORDER BY timestamp DESC', $timestamp, 0, $limit);

As an aside, if you're going to be using magic numbers (like $limit or the 3600s), you should make them persistent using variable_set(), variable_get(), and variable_del().

James
Thanks for the reply. This looks like it would work. I'll try it as soon as I finish my other project and check it up on you. Thanks again!
Danica
No problem! Like Jeremy French said, creating your own chat may be more hassle than taking one of the existing chat modules and overriding its hooks and theme functions (if the modules are written well). My code was for on a "Who's Online" block that displayed logged in users and integrated into a custom module wrapper for [RealChat](http://www.realchat.com/) to also display the chatting status of online users.
James

related questions