首先获取用户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']; }