首页 > 其他 > 详细

获取用户IP并限制时间内访问次数

时间:2021-06-16 10:29:45      阅读:26      评论:0      收藏:0      [点我收藏+]

首先获取用户IP地址:

public function ipPrevent()
    {
        if (getenv(‘HTTP_CLIENT_IP‘)) {
            $ip = getenv(‘HTTP_CLIENT_IP‘);
        }
        if (getenv(‘HTTP_X_REAL_IP‘)) {
            $ip = getenv(‘HTTP_X_REAL_IP‘);
        } elseif (getenv(‘HTTP_X_FORWARDED_FOR‘)) {
            $ip = getenv(‘HTTP_X_FORWARDED_FOR‘);
            $ips = explode(‘,‘, $ip);
            $ip = $ips[0];
        } elseif (getenv(‘REMOTE_ADDR‘)) {
            $ip = getenv(‘REMOTE_ADDR‘);
        } else {
            $ip = ‘0.0.0.0‘;
        }
        return $ip;
    }

 

我这里是拿到IP后根据标识存到redis哈希里,然后从里面拿:

一分钟 不能超过 20次

时间和次数自己更改

public static function checkWithTimes($ip,$type)
    {
        $key = "ip:$ip:$type";
        $redis = Yii::$app->redis;
        $check = $redis->exists($key);
        if($check){
            $redis->incr($key);
            $count = $redis->get($key);
            if($count > 20) {
                return [‘code‘=>1,‘msg‘=>‘刷新请求过快,请稍后重试!‘];
            }
        }else{
            $redis->incr($key);
            //限制时间为60秒
            $redis->expire($key,60);
        }
        $count = $redis->get($key);
        return [‘code‘=>0,‘msg‘=> ‘You have ‘.$count.‘ request‘];
    }

  

获取用户IP并限制时间内访问次数

原文:https://www.cnblogs.com/wxy0126/p/14888170.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!