【发布时间】:2016-04-01 05:33:45
【问题描述】:
用户将通过诸如script.php?userid=222 之类的 URL 按编号请求文件。此示例将显示文件 #222 的记录。
现在我想将每个(远程 IP)用户的文件数限制为一分钟内最多 5 条不同的记录。但是,用户应该能够多次访问同一个 id 记录。
所以用户可以访问文件 #222 任意次数,但如果(远程 IP)用户在一分钟内访问超过 5 条其他不同的记录,那么它应该会显示错误。
例如,假设在一分钟内发出以下请求:
script.php?userid=222
script.php?userid=523
script.php?userid=665
script.php?userid=852
script.php?userid=132
script.php?userid=002
然后在最后一次请求时它应该显示错误消息。
这是基本代码:
$id = $_GET['userid'];
if (!isset($_GET['userid']) || empty($_GET['userid'])) {
echo "Please enter the userid";
die();
}
if (file_exists($userid.".txt") &&
(filemtime($userid.".txt") > (time() - 3600 * $ttime ))) {
$ffile = file_get_contents($userid.".txt");} else {
$dcurl = curl_init();
$ffile = fopen($userid.".txt", "w+");
curl_setopt($dcurl, CURLOPT_URL,"http://remoteserver.com/data/$userid");
curl_setopt($dcurl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($dcurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($dcurl, CURLOPT_TIMEOUT, 50);
curl_setopt($dcurl, CURLOPT_FILE, $ffile);
$ffile = curl_exec($dcurl);
if(curl_errno($dcurl)) // check for execution errors
{
echo 'Script error: ' . curl_error($dcurl);
exit;
}
curl_close($dcurl);
$ffile = file_get_contents($userid.".txt");
}
【问题讨论】:
-
最可靠的方法是将IP地址与访问的文件ID和日期时间字段一起保存在某处(如文件或数据库)。但是,如果您有很多用户,这将产生相当多的服务器流量和 mysql 服务器上的沉重负载。具有超时的 cookie 或会话将占用更少的资源。但它们也很容易规避。 (删除 cookie 或关闭浏览器以销毁会话)。我想你必须首先在可靠性和可扩展性之间做出选择。
-
我在这里说最可靠,因为现在你不能真正依赖IP地址。 Tor 之类的浏览器可以在 5 秒内为您提供一个新的 IP 地址,只需按下一个按钮。所以我会先试探性地问自己这是否真的值得麻烦?