Example of PHP Realizing redis Restricting Access Times of Single ip and Single User
- 2021-10-15 10:12:09
- OfStack
This article describes the example of PHP to achieve redis limit single ip, single user access function. Share it for your reference, as follows:
Sometimes we need to limit the frequency of one api or page access, for example, a single ip or how many times a single user can access it in one minute
Requirements like this are easy to implement with Redis
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth("php001");
// This key Record the ip Number of visits to It can also be changed to a user id
//$key = 'userid_11100';
$key=get_real_ip();
// Limit the number of times 5
$limit = 5;
$check = $redis->exists($key);
if($check){
$redis->incr($key);
$count = $redis->get($key);
if($count > 5){
exit(' Requests are too frequent, please try again later! ');
}
}else{
$redis->incr($key);
// The limit time is 60 Seconds
$redis->expire($key,60);
}
$count = $redis->get($key);
echo ' No. 1 '.$count.' Secondary request ';
// Get client real ip Address
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;
}
?>
For more readers interested in PHP related content, please check the topics on this site: "Summary of php+redis Database Programming Skills", "Introduction to php Object-Oriented Programming", "Introduction to PHP Basic Grammar", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.