0

我正在编写一个脚本,它将限制来自给定 IP 地址的特定用户的多次访问。换句话说,给定用户将只能从同一 IP 地址访问/查看页面一次。

但是我如何比较传入的 IP 来检测这种访问呢?

我想最多跟踪 60 天的 IP。

4

6 回答 6

1

首先,不同的计算机/用户可以并且确实共享一个 IP 地址。您可能会阻止很多人访问您的网站,因为他们工作场所的某个人也访问了您的网站。话虽如此,这是我的答案。

你标记MySQL了 ,所以创建一个名为“ips”的表 - 或类似的东西。

  • ID
  • 知识产权
  • 最后访问

每当有人访问您的站点时,请检查是否在此表中找到了他们的 IP 地址,以及 lastAccess 日期是否在今天的 60 天内。如果是,则拒绝或重定向请求。如果他们的 IP 不在表中,或者日期从今天起超过 60 天,则插入/更新表以包含他们的 IP 和当前时间,然后允许他们查看请求的页面。

这不需要在数据库中完成,您可以在平面文件系统中执行类似的逻辑。但是,您将有很多文件打开、读取、写入,这可能有点令人沮丧,因为您可能会尝试写入文件,因为您当前正在尝试读取文件。

于 2012-05-01T04:11:58.420 回答
1

您需要将 IP 存储在某个数据库或平面文件中以进行比较。

假设你有一个visits这样的 MySQL 表:

`ip` varchar(255) NOT NULL,
`date_created` datetime NOT NULL,
`last_visit` datetime NOT NULL,
`visits` int(255) NOT NULL,
PRIMARY KEY (`ip`)

使用PHP我们可以获取用户的IP,在数据库中创建或更新表记录,然后做一些比较。

<?php

// Get the user's IP
$ip = getenv('REMOTE_ADDR');

// Create a database record, or update if they're been here before
$dblink = mysql_connect( 'localhost', 'username', 'password' );
mysql_select_db( 'database', $dblink );
$rs = mysql_query( "INSERT INTO visits (ip, date_created, last_visit, visits) VALUES( '$ip', NOW(), NOW(), 1 ) ON DUPLICATE KEY UPDATE `last_visit` = NOW(), visits=visits+1 ", $dblink );

// Compare database record for last visit and first visit
$rs = mysql_query( "SELECT visits, DATEDIFF( last_visit, date_created ) as sincelast FROM visits WHERE `ip` = '$ip' ");
$row = mysql_fetch_assoc( $rs );

// If this is their first visit, do one thing, otherwise, do another.
if ( $row['sincelast'] > 59 || $row['visits'] < 2 ) {
    // They visited 60+ days ago, or this is their first visit
} else {
    // This is not their first visit
}
于 2012-05-01T04:15:51.180 回答
1

如果您坚持这样做并且不使用数据库,那么您可能希望将访问数据存储在文件中并访问它以检查 ip 的首次访问时间。当然,这与理论上使用数据库几乎相同。

执行我上面建议的示例函数:(请注意,按原样使用它非常粗糙且不可靠)

function allowedIP() {
    $vFile = 'vfile'; // file to store visitor data
    $revisit = 3600*24*60; // not allowed time in seconds
    $now = time(); // visit time
    $vIP = ip2long( $_SERVER['REMOTE_ADDR'] ); // get the ip and convert to long
    $vData = ( file_exists( $vFile ) ) ? 
        unserialize( file_get_contents( $vFile ) ) : array(); // get the visit data
    if( ! isset( $vData[$vIP] ) || $now - $vData[$vIP] > $revisit ) {
        // first visit or 60 days passed since the first visit
        $vData[$vIP] = $now; // store the visit time
        file_put_contents( $vFile, serialize( $vData ) ); // save to file
        return true;
    }
    return false;
}

此功能的用法如下:

if( ! allowedIP() ) { /* ip is not allowed, notify the visitor and don't proceed */  }
于 2012-05-02T01:05:06.730 回答
0

这是一个很大的问题 - IP 并不是机器或人所独有的。那么逻辑是什么?

于 2012-05-01T04:31:20.507 回答
0

好吧,您需要在某处查找 IP 列表,因此您可以使用表或将其写入文件,然后相应地读取

于 2012-05-01T04:11:51.790 回答
0

用户$_SERVER['REMOTE_ADDR']获取用户的 IP,但这不是最好的方案,因为使用同一个代理的多个用户将在您的服务器上显示为一个 IP = 一个用户。然后将其存储在数据库中。

一个更好的主意是在用户的浏览器上设置一个 cookie,告诉您他们已经访问过。不过,他们可以作弊。但他们也可以通过使用不同的代理来欺骗 IP。

于 2012-05-01T04:12:38.163 回答