获取所有在Drupal中登录的用户 [英] Get all logged in user in Drupal

查看:99
本文介绍了获取所有在Drupal中登录的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Drupal网站,我想拥有自己的聊天室(不能使用聊天模块,因为我必须对其进行个性化设置)。我必须检索所有在线用户,但看不到任何变量。

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.

推荐答案

您可以通过查询会话表来获取所有已登录用户的列表。我假设您正在使用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().

这篇关于获取所有在Drupal中登录的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆