请告诉我如何通过访问其 session 来显示用户在线或离线。 这是 php 和 mysql 查询
header('Content-Type: application/json');
$array = array();
$res = mysql_query("SELECT * FROM `posts` WHERE status=1");
if(mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$array[] = $row['user_id']; // this adds each online user id to the array
}
}
echo json_encode($array);
我试试这段代码这是js文件
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.length > 0){ // if at least 1 is online
$('.status').each(function(){ // loop through each of the user posts
var userid = parseInt($(this).attr('id').replace('user','')); // get just the userid #
if($.inArray(userid, data) !== -1){ // if userid # in the returned data array set to online
$(this).css({background: 'green'});
} else{ // else if userid # not in the returned data array set to offline
$(this).css({background: 'grey'});
}
});
}
else { // if no one is online, set all to offline
$('.status').css({background: 'grey'});
}
}
});
}, 2000); //2s just for testing. Set to 15s when code fully works.
});
</script>
但是这段代码不是根据我的要求运行的,它是根据我每次在数据库中保存我的状态时在数据库中保存的内容运行的,然后根据它的行为给出结果。 我想要什么
- 当用户关闭其浏览器时,逻辑上它的 session 被破坏,然后我想离线显示它的状态
2.如果用户保持他的 session 那么它的状态是在线
最佳答案
没有直截了当的方法来做这个 afaik。没有合适的方法来检测用户是否关闭了他的浏览器。我见过 [在您的上下文中] 通常用于解决此特定问题的一种方法是使用 posts
表中的 last_activity_timestamp
字段。每次用户执行任何事件时,last_activity_timestamp
都会更新为新时间。
$res = mysql_query("UPDATE `posts` SET last_update_timestamp = NOW() WHERE user_id = {$currentUserId};");
然后在检查用户当前是否在线的代码中,您还可以检查自用户上次事件以来是否经过了特定时间段(比如 20 分钟),如下所示:
$res = mysql_query("SELECT * FROM `posts` WHERE status=1 AND TIMESTAMPDIFF(MINUTE, last_activity_timestamp, NOW()) > 20;");
如果用户的最后一次事件超过 20 分钟,则他实际上已注销。
关于php - 如何在 php、mysql 和 ajax session 中显示用户在线或离线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29641888/