How to handle user online status when he/she close the browser?

后端 未结 5 969
自闭症患者
自闭症患者 2021-01-06 01:47

I am having table to track user online status by setting \'is_online\' field to 1. Now User get logged in the site and shut down his/her system or power down at that time he

相关标签:
5条回答
  • 2021-01-06 02:06

    Store an time-since-last-activity. When it's been longer then a specified time - treat as if offline. You should replace the is_online with an DateTime field, and update it every time the logged in user visits the website.

    On the place you want to select all online users, instead of :

    SELECT * FROM users WHERE is_online = 1
    

    You could use:

    SELECT * FROM users WHERE is_online >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
    
    0 讨论(0)
  • 2021-01-06 02:08

    you can't. HTTP closes the connection once the page has been delivered. On the server side alone all you could do is checking if a user has requested a page within a certain amount of time.

    JavaScript might be your friend. You could use it to create a ping to a php script which then updates the last request timestamp. Once there is no more pinging, the user is gone and you'd know.

    If you have trouble with javaScript, a good point to start would be here: http://www.w3schools.com/JS/

    You might want to focus on the AJAX and HTTP request stuff.

    cu Roman

    0 讨论(0)
  • 2021-01-06 02:10

    Due to the stateless nature of the web it is not possible to know exactly when the user left your website. So you can't really trigger any code to change the mentioned value.

    As the other have said one has to store the time-since-last-activity to get an approximate idea when was the last time the user was actually doing something with the website.

    HTH :)

    0 讨论(0)
  • 2021-01-06 02:11

    You can use jquery to update your site each X time, so a function is executed each 10 seconds, as following code:

    function updateTheBBDD(){
        ... calling mysql_connect -> mysql_insert -> mysql_close
    }
    
    setInterval("updateTheBBDD()",10000);
    

    Also, when painting the user status monitor instead of consulting the BD and:

    1->green
    0->red
    

    You should:

    actual - time > 10  ---> red
    actual - time <= 10 ---> green
    
    0 讨论(0)
  • 2021-01-06 02:12

    The normal solution is to store a timestamp in the table which you update every time the user does something. Users with a recent timestamp (say, five minutes) are shown as logged in, everybody else are logged out.

    It doesn't even have to be updated on every page load. Keep a timestamp in the session with the last update time as well, and only update the table when the database flag are about to expire.

    0 讨论(0)
提交回复
热议问题