How to display the status of site users (on site/off site)

Hello. I needed to do something like this. For example, the user went to the site and it seemed to me that he was online. As soon as he came out, it seemed that he was offline. Suggest an idea.

Answer 1, authority 100%

Create an online table in the database

Fields id, time

You make a simple js script on the site that will send a request like this to the server every 30 seconds

    function check_active(){
            url: ""
        setTimeout("check_active()", 30000);

On the server, update the table online for id and write down the current timestamp. When showing the user, just see if the current time is greater than the time table + 30 means the user is offline.

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

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

If you need to receive a notification that the user has entered the site, then you do everything the same, but apart from that you make a second script that will work in your (as I understand the administrative) interface. This script should check for new users who have logged in since the last check was made. Understandably? Or explain more?

Answer 2, authority 50%

To do this, work with sessions is used, to be more precise – a table is created in the database in which the activity time of a particular user falls, i.e. with any of its actions on the page, we update the last_activityfield. We select, for example, all users who have been active within 10 minutes from the current time with the script. If you need really reliable information about who is online (not for 10 minutes), then the session is updated by Ajax every, for example, a minute, respectively, the selection is already based on activity for the last minute, in general, read about working with sessions in the database, a lot of ideas will immediately appear 🙂