简体   繁体   中英

How to count online users?

I am trying to count users that are now online, so I made these 2 queries

When logging in

$id = $_SESSION['id'];
$up = mysqli_query($conn,"UPDATE user_account SET status= 1 WHERE id='$id'");

When logging out

$id = $_SESSION['id'];
$up = mysqli_query($conn,"UPDATE user_account SET status= '0' WHERE id='$id'");

0 value is for offline while 1 is for online so it works fine, but I tried this on incognito browser mode I logged in to an account then I closed the incognito browser mode and the seassion id still exists and never turn 0 is there is way I can prevent that?

Your server can't ever know what a user does unless the user tells the server. For this reason people implement session timeouts. If there was no activity from the user for a certain period of time you assume they walked away.

You can create additional column in your database table called last_active of type DATETIME and you would update it each time a user makes a request to the server. If you want to count active users you simply make a query to fetch users active recently.

// Do this every time a user makes a request to server
$stmt = $conn->prepare('UPDATE user_account SET last_active=NOW() WHERE id=?');
$stmt->bind_param('s', $_SESSION['id']);
$stmt->execute();

// To fetch count:
$count_of_active_user = $conn->query('SELECT COUNT(*) FROM user_account WHERE last_active >= NOW() - INTERVAL 15 MINUTE')->fetch_row()[0];

Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi . Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data . Escaping is not enough!

Logically you can never know if a user closed a browser (whether it is incognito or normal mode), turned off computer, or any other possibilities. You only turn the status off when the users normally logs out using the button in your site and none of the other ways are being counted.

One way is to work with all sessions. You can find some info here . This way also does not turn off the status immediately.

Best way:

But I recommend you to use JavaScript on your site to tell the server that the user is online, each minute for example, (or any time the user interacts with the site which includes any request to the sever). And set a DATETIME value in database to store the last activity of each user on the site, so you can set a limit and say for example if it's more than 5 minuets from a user's last activity the the user is offline, else he/she is online.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM