开发者

User limit for my PHP app - with example code

开发者 https://www.devze.com 2023-01-22 22:12 出处:网络
I have a PHP app that I am looking to limit the number of users that can be active at any given time. I would like to keep it as light as possible as the reason for implementing it is because our curr

I have a PHP app that I am looking to limit the number of users that can be active at any given time. I would like to keep it as light as possible as the reason for implementing it is because our current server can not handle the load - thus this is a temporary solution until we can upgrade. We store our sessions in memcache so I have written the following script to count the active sessions and store it in a flat file - this script is run every 5 mins.

<?php
  $memcache = new Memcache; 
  $memcache->connect('127.0.0.1', 11211);
  $activeSessions = $memcache->getStats(); 


$file_content = <<<TEXT
<?php

\$activeSessions = {$activeSessions['curr_items']};

?>
TEXT;

file_put_contents("activesessions.php", $file_content);
?>

Now at the top of each page it is easy to find out how many users are currently active... my problem now is if there is more than the limit to stop more people creating sessions. The reason why this is a problem is I have no way of telling if the user loading the page already has an active session without doing something like:

    <?php

include ('activesessions.php');
//uid is the users facebook id
session_id(md5($uid.$secret));
session_start();
if ($activeSessions > $limit && empty($_SESSION))
{
   session_destroy();
   include('limit_message.php');
   exit;
}
?>

which should do the trick but in the process it will create a session to check if the session exists :S... thus skewing my active session count.

So essentially I have a solution... my question though is does anyone have a better one? If however you think my solution is the best开发者_JS百科 one please comment or up-vote to let me know :D

Please help :)


If you call session_id() without any parameters it will return the user's current sesssion id or a blank string if there is not current session id, as stated in the PHP function manual. Based on what you have, you'll want to do something like this:

include ('activesessions.php');
//uid is the users facebook id

if ($activeSessions > $limit && session_id() == '')
{
   include('limit_message.php');
   exit;
}

session_id(md5($uid.$secret));
session_start();

This is just a shortcut that checks if a cookie is set with the session name, and if so that the value is a valid session id string.

0

精彩评论

暂无评论...
验证码 换一张
取 消