开发者

Get all the logged-in user

开发者 https://www.devze.com 2023-01-04 12:45 出处:网络
I want to have my own chat. (I can\'t use the Chat module because I have to personalize it.) I ha开发者_运维问答ve to retrieve all the users who are online, but I can\'t see any variable for that.

I want to have my own chat. (I can't use the Chat module because I have to personalize it.) I ha开发者_运维问答ve to retrieve all the users who are online, 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 logged-in users.


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().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号