Count and limit the number of users on my app

前端 未结 3 783
不思量自难忘°
不思量自难忘° 2020-12-11 11:35

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 act

相关标签:
3条回答
  • 2020-12-11 12:15

    May be you web-server can limit maximum number of concurrent clients? (But this can affect fetching images/other static content)

    0 讨论(0)
  • 2020-12-11 12:18

    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.

    0 讨论(0)
  • 2020-12-11 12:31

    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...
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题