Reputation: 5012
I have a LAMP server, my main application page demands new ajax requests every 3 seconds. To prevent the server from being overloaded, I want to block normal viewers (those who arene't paid clients) to open only a single instance of the application page, whereas the paid clients can open multiple instances of the page
Any I Ideas?
Thanks
Upvotes: 0
Views: 336
Reputation: 7541
Assuming you have some cookie set on the user, when the AJAX request arrives it will also contain the cookie. Write a function to validate the cookie (eg: isUserLoggedIn()
) and monitor how often the user requests a page:
$minLoggedOutRequestDelay = 3;
// Set up the variable for the first time
if (! isset($_SESSION["lastAjaxRequest"]))
{
$_SESSION["lastAjaxRequest"] = 0;
}
if ($_SESSION["lastAjaxRequest"] - microtime() > $minLoggedOutRequestDelay
AND (! isUserLoggedIn()))
{
// Do something to stop the request from going through
// or maybe just log it
}
$_SESSION["lastAjaxRequest"] = microtime();
// Continue as normal
This will cause only one tab to work at once. If they have multiple open, the 'active' tab may switch between tabs due to network latency. To check based on how many tabs are open and make one work perfectly and the others not at all, you'll need a random number generated on page load. Include it as part of the AJAX request to tell the different pages apart (eg: ...&pageRandomNumber=828918&...
:
$minLoggedOutRequestDelay = 3;
$maxLoggedOutPages = 1;
// Set up the array in case its the first time
if (! isset($_SESSION["lastAjaxRequest"]))
{
$_SESSION["lastAjaxRequest"] = array();
}
// Trim inactive pages from the array
foreach ($_SESSION["lastAjaxRequest"] as $pageRandomNumber => $lastTime)
{
if ($lastTime - microtime() > $minLoggedOutRequestDelay * 2)
{
unset($_SESSION["lastAjaxRequest"][$pageRandomNumber]);
}
}
// Make sure the current page is initialised
if (! isset($_SESSION["lastAjaxRequest"][$_REQUEST["pageRandomNumber"]]))
{
$_SESSION["lastAjaxRequest"][$_REQUEST["pageRandomNumber"]] = 0;
}
if ((! isUserLoggedIn())
AND count($_SESSION["lastAjaxRequest"]) > $maxLoggedOutPages)
{
// Do something to stop the request from going through
// or maybe just log it
}
$_SESSION["lastAjaxRequest"][$_REQUEST["pageRandomNumber"]] = microtime();
// Continue as normal
Its possible for pageRandomNumber to be the same on multiple tabs, but highly unlikely given sufficient digits.
Upvotes: 1