注意:我不打算转义示例中的数据,但您需要使用 mysqli 或 PDO 进行转义
创建一个表logged_in_users
或类似的东西,其中一些列是这样的:
create table logged_in_users(
user_id int unsigned,
login_date datetime,
hash_key char(32),
unique key user_hash_key(user_id, hash_key)
);
当用户登录时,删除旧记录,然后添加新成员,如下所示:
$hash_key = md5(time().uniqid().rand(0,1000)); // Create a unique key
$_SESSION["hashkey"] = $hash_key;
// Remove the inactive members (this uses 10 minutes)
delete from logged_in_users where login_date > date_sub(now(), interval 10 minute);
// Add the user
insert ignore into logged_in_users (user_id, login_date, hash_key) values (123, now(), '$hash_key');
当用户加载页面时,您应该检查用户是否仍有记录,如果他/她不喜欢这样,请插入一条记录:
$hash_key = $_SESSION["hashkey"];
insert ignore into logged_in_users (user_id, login_date, hash_key) values (123, now(), '$hash_key');
然后,当您想知道有多少人登录时,您可以执行以下操作:
// Total people for a particular member
select count(*) as total from logged_in_users where user_id = 123;
// Total people logged in
select count(*) as total from logged_in_users;
// Total members logged in (not people)
select count(distinct user_id) as total from logged_in_users;
最后,当用户注销时,像这样删除它们:
$hash_key = $_SESSION["hashkey"];
delete from logged_in_users where user_id = 123 and hash_key = '$hash_key';