Count and limit the number of users on my app

天大地大妈咪最大 提交于 2019-11-28 12:58:04

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!