开发者

Restrict access to pages in php

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 applic开发者_如何学编程ation page, whereas the paid clients can open multiple instances of the page

Any I Ideas?

Thanks


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜