限制访问php中的页面

时间:2011-02-16 08:18:13

标签: php

我有一台LAMP服务器,我的主应用程序页面每隔3秒就要求新的ajax请求。为了防止服务器过载,我想阻止普通的查看者(那些没有付费客户端)只打开应用程序页面的单个实例,而付费客户端可以打开页面的多个实例

我的想法吗?

由于

1 个答案:

答案 0 :(得分:1)

假设您在用户上设置了一些cookie,当AJAX请求到达时,它也将包含cookie。编写一个函数来验证cookie(例如:isUserLoggedIn())并监控用户请求页面的频率:

$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

这将导致一次只能使用一个选项卡。如果它们有多个打开,则“活动”选项卡可能会因网络延迟而在选项卡之间切换。要根据打开的标签数量进行检查并使其中一个完全正常工作而其他标签完全无效,您需要在页面加载时生成一个随机数。将其作为AJAX请求的一部分包含在内,以区分不同的页面(例如:...&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

在多个选项卡上,pageRandomNumber可能是相同的,但如果数字足够,则极不可能。