Log in

View Full Version : A script to allow only a certain amount of users on a webpage?



jacksont123
03-01-2007, 10:11 PM
Can anyone please show me a php script that only allows 300 users on a page at once, but makes the 301st user and so on be redirected to another page?

Twey
03-01-2007, 10:13 PM
Since HTTP is stateless, it's impossible to do this. The best you can do is only allow the page to be requested 300 times every, say, five minutes.

jacksont123
03-01-2007, 10:17 PM
To rephrase my first post, I kinda want a function like the one in FTP that only allows the first x users, then blocks the rest until one of the first x users leaves.
If I can't do what I meant in the first post, how would I be able to do what you suggested?

Twey
03-02-2007, 01:44 AM
Store a list of last-seen times in a database. Each time somebody accesses the page:Check if there are more than 300 times in the database If so, redirect the user Otherwise:Add the current time to the database Remove any times more than five minutes ago from the database Serve the page

boxxertrumps
03-02-2007, 02:08 PM
logical error in there twey.

once you have 300 people, noone can get in, and the database isnt checked for timeouts.
This:
Remove any times more than five minutes ago from the database
Should be first.

Twey
03-02-2007, 03:01 PM
Ah! You're right.Remove any times more than five minutes ago from the database Check if there are more than 300 times in the database If so, redirect the user Otherwise:Add the current time to the database Serve the page

boxxertrumps
03-02-2007, 04:18 PM
<?php
$contents = @file_get_contents("includes/online.txt");
$array = explode("\r\n",$contents);
$curr = time();
foreach($array){
$dif = $curr-$array;
if($dif >= "300") {
unset($array);
}
};
$num = count($array);
if($num >= "299") {
$array[] = $curr;
?>

WEB PAGE GOES HERE

<?php } else { ?>

Alternate web page/meta redirects

<?php
};
$towrite = implode("\r\n",$array);
$handle = fopen("includes/online.txt","w+");
fwrite($handle,$towrite);
fclose($handle);
?>

untested. flatfile DB. 300 requests every 5 min(300 sec.)

Twey
03-02-2007, 08:43 PM
$contents = @file_get_contents("includes/online.txt");
$array = explode("\r\n",$contents); Rather, $arr = file('includes/online.txt'); The former will break on UNIX-based servers, which use \n rather than \r\n to signify a linebreak.