获取所有登录用户 [英] Get all the logged-in user
问题描述
我想进行自己的聊天.(我不能使用聊天模块,因为必须对其进行个性化设置.)我必须检索所有在线用户,但是看不到任何变量.
I want to have my own chat. (I can't use the Chat module because I have to personalize it.) I have 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.
推荐答案
您可以通过查询会话表来获取所有已登录用户的列表.我假设您正在使用Drupal 6.
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);
}
该查询排除了 uid = 0
的会话,因为这些会话是匿名用户. $ users
是用户对象的数组,如 Drupal API文档.
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.
如果您已经知道要使用的用户对象的一部分(例如,用户ID和名称),可以通过以下方法进行优化:删除while循环中的user_load()并向查询中添加与users表的联接,因为每个user_load()都会进行一个附加查询.以下将为您提供已登录用户的ID和名称的列表:
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);
您可能还想限制返回的用户数.例如,也许您想(最多)吸引访问该站点的最后10个登录用户:
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);
顺便说一句,如果您要使用魔术数字(例如$ limit或3600s),应使用variable_set(),variable_get()和variable_del()使它们持久化.
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().
这篇关于获取所有登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!