- <?php
- /**
- * @author flynetcn
- */
- class utils_spam
- {
- /**
- * 用cookie对用户在某个时间范围内的提交次数进行计数
- * @param str $counterKey cookie键
- * @param int $intervalSec 多少秒内
- * @return int 本次累计后的计数
- */
- public static function submitCounter($counterKey, $intervalSec=300)
- {
- if (!isset($_COOKIE[$counterKey])) {
- $_COOKIE[$counterKey] = array('c'=>1, 't'=>time());
- } else {
- if (!is_array($_COOKIE[$counterKey])) {
- $_COOKIE[$counterKey] = unserialize(base64_decode($_COOKIE[$counterKey]));
- }
- if (time() - $_COOKIE[$counterKey]['t'] > $intervalSec) {
- $_COOKIE[$counterKey] = array('c'=>1, 't'=>time());
- } else {
- $_COOKIE[$counterKey]['c']++;
- }
- }
- setcookie($counterKey, base64_encode(serialize($_COOKIE[$counterKey])), time()+$intervalSec);
- return $_COOKIE[$counterKey]['c'];
- }
- /**
- * 获取当前计数值
- * @param str $counterKey cookie键
- * @return int 当前计数
- */
- public static function getSubmitCounter($counterKey)
- {
- if (!isset($_COOKIE[$counterKey])) {
- return 0;
- } else {
- if (!is_array($_COOKIE[$counterKey])) {
- $_COOKIE[$counterKey] = unserialize(base64_decode($_COOKIE[$counterKey]));
- }
- return $_COOKIE[$counterKey]['c'];
- }
- }
- }
10-09 10:21