php 如何通过用户ID检查用户是否在线?

nxowjjhe  于 2023-05-27  发布在  PHP
关注(0)|答案(2)|浏览(266)

我想在我的网站上显示一个在线状态,如果其他用户在线。例如,如果用户A想知道用户B是否可用,我想显示一个在线标志。
我知道WordPress中有一个名为is_user_logged_in()的函数,但该函数仅适用于当前用户。https://developer.wordpress.org/reference/functions/is_user_logged_in/那么有没有人有一个想法,我可以得到这个做吗?
这就是逻辑:

if ( user_online( $user_id ) ) {
    return 'Online';
} else {
    return 'Absent';
}
bejyjqdl

bejyjqdl1#

您可以使用Transients API来获取用户的状态。在init上创建一个用户在线更新函数。例如:

// get logged-in users
$logged_in_users = get_transient('online_status');

// get current user ID
$user = wp_get_current_user();

// check if the current user needs to update his online status;
// status no need to update if user exist in the list
// and if his "last activity" was less than let's say ...15 minutes ago  
$no_need_to_update = isset($logged_in_users[$user->ID]) 
    && $logged_in_users[$user->ID] >  (time() - (15 * 60));

// update the list if needed
if (!$no_need_to_update) {
  $logged_in_users[$user->ID] = time();
  set_transient('online_status', $logged_in_users, $expire_in = (30*60)); // 30 mins 
}

这应该在每个页面加载时运行,但仅在需要时才更新 transient 。如果您有大量用户在线,您可能希望增加“最后一次活动”时间范围以减少数据库写入,但15分钟对于大多数站点来说已经足够了。
现在要检查用户是否在线,只需查看该 transient 内部,看看某个用户是否在线,就像上面所做的那样:

// get logged in users
$logged_in_users = get_transient('online_status');

// for eg. on author page
$user_to_check = get_query_var('author'); 

$online = isset($logged_in_users[$user_to_check])
   && ($logged_in_users[$user_to_check] >  (time() - (15 * 60)));

如果没有任何活动30分钟后瞬变失效。但是如果你有用户一直在线,它不会过期,所以你可能想通过在twice-daily event或类似的东西上挂接另一个函数来定期清理这个 transient 。此函数将删除旧的$logged_in_users条目...
来源:https://wordpress.stackexchange.com/a/34434

nhaq1z21

nhaq1z212#

First get the user id of the user B by 

    $user_id_B = get_current_user_id();

    Now here give the condition for the particular user B to check whether he is online or not

if(is_user_logged_in()){
    if( $user_id_B == 'user id of B')
    {
        return 'Online'; (or echo 'online';)
    }
}
By this you will get the presence of user B.

相关问题