Hello. I have a need to do such a thing. For example, the user went to the site and I thought he was online. As soon as he left, it seemed that he was offline. Suggest any idea.

    2 answers 2

    Create a table online in the database

    Fields id, time

    On the site you make a simple js script which, once every 30 seconds, will send a request to the server

    <script> check_active(); function check_active(){ $.ajax({ url: "http://myhost.com/check_online/?id=%USER_ID%" }); setTimeout("check_active()", 30000); } </script> 

    On the server, update the table online for id; write the current timestamp. When displaying a user, simply see if the current time is more than the time of the table + 30 means the user is offline.

    You can simply add the time field to the user table.

    This is if you need to update the user's activity status very often. If this is not required, then you can simply update the status when the page is reloaded.

    If you need a notification that a user has come to the site, you do the same thing, but other than that you do the second script, which will work in your (as I understand it administrative) interface. This script should check for new users who have logged in since the last time the check was performed. Clear? Or explain in more detail?

    • It’s not necessary to add it to the users table exactly ... This solution is normal if the activity of online users is all that is necessary ... By the way, you can also send id = 0 for example if the user is unauthorized and count, as well as the number of hares on the site: ) Only then it will be necessary to somehow distinguish them, but this can be done for example by passing the session identifier - Zowie
    • What to add to the table of users is not worth it. That's why I immediately described the need to create a new one) About id = 0 - a good idea) - Daniel Vendolin

    To do this, work with sessions is used, to be more precise - a table is created in the database in which the time of activity of one or another user lays down, i.e. for any of its actions on the page, we update the last_activity field. By the script, we select, for example, all users who have been active for 10 minutes from the current time. If you really need accurate information about who is online (not for 10 minutes), then the session is updated every minute, for example, a minute, respectively, the sample is already active in the last minute, read about working with sessions in the database, a lot of ideas will immediately appear :)