Home  >  Article  >  Backend Development  >  Detailed explanation of PHP interface access frequency limit

Detailed explanation of PHP interface access frequency limit

藏色散人
藏色散人forward
2021-03-01 13:42:525763browse

This article will introduce the PHP interface access frequency limit to everyone. I hope it will be helpful to friends in need!

I found that many restrictions on the Internet are only restrictions on access within 1 minute (or a certain time).

For example, if the limit is 10 times per minute, then I access 10 times in 59 seconds, and then the key expires again, and I can access it again in the next minute. This restriction is simply unreasonable.

So I have my idea.

Just upload the code.

/**
 * @param $uid
 * @return bool|int
 * 检测用户接口访问频率
 */
function api_frequency_visits ($uid) {
    $key = "user:{$uid}:api:frequency";
    $redis = new Redis();
    $redis->connect('127.0.0.1');
    $data = $redis->hGetAll($key);
    //需要删除的key
    $del_key = [];
    //时间内访问的总次数
    $total = 0;
    //时间内最大访问次数
    $max_frequency = 10;
    //当前时间
    $now_time = time();
    //限制时间
    $limit_time = 60;
    foreach ($data as $time=>$count) {
        if ($time < $now_time - $limit_time) {
            $del_key[] = $time;
        } else {
            $total += $count;
        }
    }
    //存在需要删除的key
    if ($del_key) {
        $redis->hDel($key, ...$del_key);
    }
    if ($total >= $max_frequency) {
        return false;
    }
    return $redis->hIncrBy($key, $now_time, 1);
}
$uid = 1;
$result = api_frequency_visits($uid);
if (!$result) {
    echo  json_encode(['code'=>0, 'msg'=>'操作过于频繁', 'data'=>[]]);die;
}
echo  json_encode(['code'=>1, 'msg'=>'', 'data'=>[
    'uid'=>$uid,
    'other'=>rand()
]]);die;

The time limit and the number of times can be modified, including changing to the limit you want based on the user ID, such as IP, etc.

The key expiration time can also be added.

Recommended: "PHP Video Tutorial"

The above is the detailed content of Detailed explanation of PHP interface access frequency limit. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete