“晚风吹人醒 万事藏于心 
        我没说不公平 也没说苦 我说我知道了”
posts - 70,comments - 1,views - 26177

调用方法 

复制代码
// 检查请求是否来自爬虫
    if ($this->isCrawler()) {
        $this->ajaxReturn(array('status'=>'0','info'=>'爬虫访问'));
    }
    //限制访问次数
    $result = $this->api_frequency_visits(UID);
    if (!$result) {
        $this->ajaxReturn(array('status'=>'0','info'=>'访问次数过多'));
     }
复制代码

 

复制代码
// 检查用户代理是否像常规浏览器
    function isCrawler() {
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        if(!$userAgent){
            return true; //true 表示是爬虫
        }
        $knownCrawlers = [
            'Googlebot', 'Bingbot', 'Slurp', 'DuckDuckBot', 'Baidu', 'Yahoo', 'Yandex',
        ];
        foreach ($knownCrawlers as $crawler) {
            if (strpos($userAgent, $crawler) !== false) {
                return true;
            }
        }
        if(substr($userAgent, 0,16)=="python-requests/" or substr($userAgent, 0,14)=="Python-urllib/"){
            return true;
        }
        return false;
    }
/**
 * @param $uid
 * @return bool|int
 * 检测用户接口访问频率
 */
function api_frequency_visits ($uid) {
    $key = "user:{$uid}:api:frequency";
    $redis = new Redis();
    $redis->connect('127.0.0.1');
    $data = $redis->hGetAll($key);
    //需要删除的key
    $del_key = [];
    //时间内访问的总次数
    $total = 0;
    //时间内最大访问次数
    $max_frequency = 10;
    //当前时间
    $now_time = time();
    //限制时间
    $limit_time = 60;
    foreach ($data as $time=>$count) {
        if ($time < $now_time - $limit_time) {
            $del_key[] = $time;
        } else {
            $total += $count;
        }
    }
    //存在需要删除的key
    if ($del_key) {
        $redis->hDel($key, ...$del_key);
    }
    if ($total >= $max_frequency) {
        return false;
    }
    return $redis->hIncrBy($key, $now_time, 1);
}
复制代码

 

posted on   诗里刻画的影子  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示