前言:

我有一个接口站 https://api.oioweb.cn 有一个接口发现被恶意调用了,需要想对IP进行访问频次限制,服务器上正好有Redis,就用这个对IP访问频次进行限制是个不错的选择,那来直接上代码吧!

实现代码:

<?php
/**
 * time:2019-10-21 14:24:00
 * blog: blog.oioweb.cn
 * author:教书先生
 */
$redis = new Redis();
$redis->connect('127.0.0.1', 6379); //连接 Redis
if (!$redis->exists(get_real_ip())){
    //第一次访问
    $redis->set(get_real_ip(),1,5*60); // 设置5分钟过期时间并设置初始值1
}else{
    //已经记录过IP
    if ($redis->get(get_real_ip())<30){ //判断IP有没有到达拉黑阈值
        $redis->incr(get_real_ip()); //次数加一
    }else{
        echo '此IP已拉黑,5分钟内请求已达到:'.$redis->get(get_real_ip()).'次';
    }
}
function get_real_ip($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
最后修改:2020 年 11 月 12 日
如果觉得我的文章对你有用,请随意赞赏