1. <?php
  2. /**
  3.  * @author flynetcn
  4.  */
  5. class utils_spam
  6. {
  7.     /**
  8.      * 用cookie对用户在某个时间范围内的提交次数进行计数
  9.      * @param str $counterKey cookie键
  10.      * @param int $intervalSec 多少秒内
  11.      * @return int 本次累计后的计数
  12.      */
  13.     public static function submitCounter($counterKey, $intervalSec=300)
  14.     {
  15.         if (!isset($_COOKIE[$counterKey])) {
  16.             $_COOKIE[$counterKey] = array('c'=>1, 't'=>time());
  17.         } else {
  18.             if (!is_array($_COOKIE[$counterKey])) {
  19.                 $_COOKIE[$counterKey] = unserialize(base64_decode($_COOKIE[$counterKey]));
  20.             }
  21.             if (time() - $_COOKIE[$counterKey]['t'] > $intervalSec) {
  22.                 $_COOKIE[$counterKey] = array('c'=>1, 't'=>time());
  23.             } else {
  24.                 $_COOKIE[$counterKey]['c']++;
  25.             }
  26.         }
  27.         setcookie($counterKey, base64_encode(serialize($_COOKIE[$counterKey])), time()+$intervalSec);
  28.         return $_COOKIE[$counterKey]['c'];
  29.     }

  30.     /**
  31.      * 获取当前计数值
  32.      * @param str $counterKey cookie键
  33.      * @return int 当前计数
  34.      */
  35.     public static function getSubmitCounter($counterKey)
  36.     {
  37.         if (!isset($_COOKIE[$counterKey])) {
  38.             return 0;
  39.         } else {
  40.             if (!is_array($_COOKIE[$counterKey])) {
  41.                 $_COOKIE[$counterKey] = unserialize(base64_decode($_COOKIE[$counterKey]));
  42.             }
  43.             return $_COOKIE[$counterKey]['c'];
  44.         }
  45.     }
  46. }


10-09 10:21