I need to implement a system to limit the number of users that can concurrently use my app. I am thinking the best way to go is to count the number of sessions currently active and then limit based on that.
How can I count the number of sessions currently active. I am using memcached to store my sessions if that makes a difference
I think the easiest way is to intercept the session's open
, destroy
and gc
callbacks (using session_set_save_handler()
) and increment/decrement a session count value within memcached. Something like:
class Memcache_Save_Handler {
private $memcached;
public function open($save_path, $name) {
$session_count = (int)$this->memcached->get('session_count');
$this->memcached->set('session_count', ++$session_count);
// rest of handling...
}
public function destroy($id) {
$session_count = (int)$this->memcached->get('session_count');
$this->memcached->set('session_count', --$session_count);
// rest of handling...
}
}
I don't know any way to count every active sessions at a given time in PHP. I've always used a database for this, where I'd store the IP address and the current date (NOW() SQL function). Then, I you can do a query like this (MySQL syntax) :
SELECT COUNT(*) as active_users
FROM logged_users
WHERE last_action > NOW() - INTERVAL 5 MINUTE;
You can then choose to display the page or forbid the user to see the website.
May be you web-server can limit maximum number of concurrent clients? (But this can affect fetching images/other static content)