Home > php教程 > php手册 > 检查/设置用户访问频率

检查/设置用户访问频率

WBOY
Release: 2016-06-07 11:38:19
Original
1308 people have browsed it

检查/设置用户访问频率 指定 user_marked在 time_slot 秒内最多访问 count次;
/**<br>  * 检查/设置用户访问频率 指定 user_marked在 time_slot 秒内最多访问 count次;<br>  * @param $lime_slot 时间片 单位秒<br>  * @param $count 整数<br>  * @param $user_marked 用户唯一标示,默认为客户端IP<br>  * @return array('status'=>1,'info'=>'') <br>  * @author leeyi <leeyisoft><br>  */<br> function check_rate_limiting($time_slot, $count, $user_marked='') {<br>     $user_marked = empty($user_marked) ? get_client_ip() : $user_marked;<br>     $cache_key = 'rate.limiting:'.$user_marked;<br>     $redis = new \Redis;<br>     $options = array (<br>         'host'          => C('REDIS_HOST') ? C('REDIS_HOST') : '127.0.0.1',<br>         'port'          => C('REDIS_PORT') ? C('REDIS_PORT') : 6379,<br>         'timeout'       => C('DATA_CACHE_TIMEOUT') ? C('DATA_CACHE_TIMEOUT') : false,<br>     );<br>     $res = $redis->connect($options['host'], $options['port'], $options['timeout']);<br>     $ret = array('status'=>0, 'info'=>'');<br>     if( false===$res) {<br>         $ret['info'] = '链接Redis失败';<br>         return $ret;<br>     }<br>     $redis->expire($cache_key, $time_slot); // 设置过期时间<br>     $list_len = $redis->llen($cache_key);<br>     if( $list_len         $redis->lpush($cache_key, NOW_TIME);<br>         $ret['status'] = 1;<br>     } else {<br>         $datetime = $redis->lindex($cache_key, -1); // -1 标示列表最后一个元素<br>         if( (NOW_TIME-$datetime)             $ret['info'] = '访问频率超过了限制,请稍后重试。';<br>             // $redis->ltrim($cache_key, -1, 0); //清空列表<br>         } else {<br>             $redis->lpush($cache_key, NOW_TIME);<br>             // <br>             $redis->ltrim($cache_key, 0, $count-1);<br>             $ret['status'] = 1;<br>         }<br>     }<br>     1==$ret['status'] && $ret['info'] = $list_len+1;<br>     return $ret;<br> <br> }</leeyisoft>

AD:真正免费,域名+虚机+企业邮箱=0元

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template