我正在尝试创建一个网络调查问卷,但我不希望同一个人使用相同的IP在一小时内提交不止一次,我使用PHP,我认为我需要
$_SERVER['REMOTE_ADDR']
用来获取客户端IP和存储在会话或数据库中,然后使用它来比较新的IP,我不知道它是否正确,不知道如何在PHP中精确实现这一点,任何人都可以帮助我,提前感谢!
提交调查时:
/* Tracking table structure: `id` INT(11) unsigned NOT NULL AUTO_INCREMENT `client_ip` VARCHAR(15) NOT NULL `submitted_time` DATETIME NOT NULL */ $query = "SELECT count(`id`) AS 'count' FROM `tracking_table` WHERE `client_ip` = '".mysqli_real_escape_string($link, $_SERVER['REMOTE_ADDR'])."' AND `submitted_time` > '".date('Y-m-d H:i:s',strtotime('-1 hour'))."' LIMIT 1"; $result = mysqli_fetch_assoc(mysqli_query($link, $query)); if ($result['count'] > 0) { echo "You have already submitted within the last hour"; exit; } // process survey here $query = "INSERT INTO `tracking_table` (`client_ip`, `submitted_time`) VALUES ('".mysqli_real_escape_string($link, $_SERVER['REMOTE_ADDR'])."', ".date('Y-m-d H:i:s').")"; mysqli_query($link, $query);
但是,您可能会发现这不是一个好的要求 - 有许多有效的情况,多个用户可能使用相同的IP地址(例如,学生住宿).您可能通过强加此限制来阻止有效提交.
编辑
以下是如何使用cookie执行此操作的基本概述(考虑到下面讨论的限制).
我们的cookie系统适用于一对值.ckv_1
将保留上次调查提交的时间戳.ckv_2
将持有基于时间戳和盐的哈希值,以阻止人们搞砸cookie.显然,如果两个cookie都被删除,我们将无法检测到它,但至少这提供了某种验证:
function get_cookie_hash ($timestamp, $salt) { return md5("Extra random static string; TS: $timestamp; Salt: $salt; Extra random static string."); } $cookieSalt = 'Th1si54rAnd0MsTr1nG!'; // If at least one of the cookies was returned, validate the request if (!empty($_COOKIE['ckv_1']) || !empty($_COOKIE['ckv_2'])) { $valid = FALSE; do { // Wrapped in a do-while to allow us to break out easily // Make sure both value are set if (empty($_COOKIE['ckv_1']) || empty($_COOKIE['ckv_2'])) break; // Get old timestamp as integer $oldTS = hexdec($_COOKIE['ckv_1']); // Make sure timestamp is more than one hour old, and the hash cookie matches it if ($oldTS > (time() - 3600) || $_COOKIE['ckv_2'] != get_cookie_hash($oldTS, $cookieSalt)) break; // OK if you get here $valid = TRUE; } while (FALSE); if (!$valid) { echo "Sorry - you cannot submit a survey more than once in an hour."; exit; } } // process survey here // Set the tracking cookies after processing (but before any output!) // We'll set them as HTTP only to help prevent XSS-type attacks $cookieTime = time(); setcookie('ckv_1', dechex($cookieTime), 7200, '', '', FALSE, TRUE); setcookie('ckv_2', get_cookie_hash($cookieTime, $cookieSalt), 7200, '', '', FALSE, TRUE);