Created
October 3, 2019 02:30
-
-
Save lepig/9fd4695c02f4054858adcf9cccc6eb48 to your computer and use it in GitHub Desktop.
使用redis进行ip限速
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$redis = new Redis(); | |
$redis->connect('127.0.0.1', 6379); | |
$redis->auth("php001"); | |
//这个key记录该ip的访问次数 也可改成用户id | |
//$key = 'userid_11100'; | |
$key=get_real_ip(); | |
//限制次数为5 | |
$limit = 5; | |
$check = $redis->exists($key); | |
if($check){ | |
$redis->incr($key); | |
$count = $redis->get($key); | |
if($count > 5){ | |
exit('请求太频繁,请稍后再试!'); | |
} | |
}else{ | |
$redis->incr($key); | |
//限制时间为60秒 | |
$redis->expire($key,60); | |
} | |
$count = $redis->get($key); | |
echo '第 '.$count.' 次请求'; | |
//获取客户端真实ip地址 | |
function get_real_ip(){ | |
static $realip; | |
if(isset($_SERVER)){ | |
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ | |
$realip=$_SERVER['HTTP_X_FORWARDED_FOR']; | |
}else if(isset($_SERVER['HTTP_CLIENT_IP'])){ | |
$realip=$_SERVER['HTTP_CLIENT_IP']; | |
}else{ | |
$realip=$_SERVER['REMOTE_ADDR']; | |
} | |
}else{ | |
if(getenv('HTTP_X_FORWARDED_FOR')){ | |
$realip=getenv('HTTP_X_FORWARDED_FOR'); | |
}else if(getenv('HTTP_CLIENT_IP')){ | |
$realip=getenv('HTTP_CLIENT_IP'); | |
}else{ | |
$realip=getenv('REMOTE_ADDR'); | |
} | |
} | |
return $realip; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment