Php – How will I restrict the number of users logged in based on session

MySQLPHP

I have a software (in cloud) with so many registered users.

I want to restrict the number of users logged in at a time to certain number (configuration based, let's say 100).

If the 101 user tries to login he should be placed in queue with priority 1, subsequently 102 user should be 2 in queue, I know at every time a logged in users request is hitting the server the sess_file access time will be updated.

What should be the logic from here? Should I check the last accessed time of all the sess_file and log-out the uses that are idle? and how will I manage the waiting queue?

Software is done with PHP-MySQL.

When the user is logged in I mark the column as logged in in user table, and when the log-in page is loaded if the total logged in user count is 100, the 101 user who is trying to log-in is directed to a intermediate page which will check via ajax call fired at an interval of 5 mins that if any user is logged out. If a slot is available it redirects to the log-in page, automatically logs in and redirects to the user dashboard. But I want to know any better practice is there.

Mostly I want to know the invalidation of logged in user by checking the access time of sess_file is the right way to do it?

Best Answer

When the user is logged in I mark the column as logged in in user table, and when the log-in page is loaded if the total logged in user count is 100, the 101 user who is trying to log-in is redirected

I would alter that approach to allow all users to log in, but if the number of active users exceeds 100 then redirect the new user to a holding page. Their session is created but they are now in a queue to leave the holding page.

This makes giving users access a lot easier, because you no longer have to track the 100 logged in users. You can simply order by the record ID of session table. This approach assumes you are tracking sessions with a session table in your database. When a user logs out you delete their session record from the table.

It's assumed you are using an auto-increment integer for your ID column.

To check if the current user should be place on hold is very easy.

SELECT `id` FROM `sessions` ORDER BY `id` LIMIT 1;

Using the first id in the table you can quickly check if the user is in the top 100 sessions.

$id = query('SELECT `id` FROM `sessions` ORDER BY `id` LIMIT 1');
if($my_session_id > $id+100)
{
   // this user is placed in holding
}
else
{
   // this user has full access
}

As soon as a record above the current use is deleted. They automatically move up in the queue.

Related Topic