qize

php接口限流主要是防止高并发造成服务器扛不住的情况下,需要限制数据的获取,简单实现就是结合redis实现。

 

 

 1 <?php
 2  
 3 /**
 4  * api 接口限流
 5  *
 6  */
 7  
 8 class api
 9 {
10  
11     public function get_client_ip($type = 0) {
12         $type       =  $type ? 1 : 0;
13         static $ip  =   NULL;
14         if ($ip !== NULL) return $ip[$type];
15         if (isset($_SERVER[\'HTTP_X_FORWARDED_FOR\'])) {
16             $arr    =   explode(\',\', $_SERVER[\'HTTP_X_FORWARDED_FOR\']);
17             $pos    =   array_search(\'unknown\',$arr);
18             if(false !== $pos) unset($arr[$pos]);
19             $ip     =   trim($arr[0]);
20         }elseif (isset($_SERVER[\'HTTP_CLIENT_IP\'])) {
21             $ip     =   $_SERVER[\'HTTP_CLIENT_IP\'];
22         }elseif (isset($_SERVER[\'REMOTE_ADDR\'])) {
23             $ip     =   $_SERVER[\'REMOTE_ADDR\'];
24         }
25         // IP地址合法验证
26         $long = ip2long($ip);
27         $ip   = $long ? array($ip, $long) : array(\'0.0.0.0\', 0);
28         return $ip[$type];
29     }
30  
31     public function test()
32     {
33  
34         //接口时间限流,这种方式可以防止钻时间漏洞无限的访问接口 比如在59秒的时候访问,就钻了空子
35         $redis = new Redis();
36         $redis->connect(\'127.0.0.1\', 6379);
37         $ip = $this->get_client_ip(true);
38         $len = $redis->lLen($ip);
39         if($len === 0)
40         {
41             $redis->lPush($ip,time());
42             echo "访问1次<br>";
43             $redis->expire($ip,60);
44         }else{
45             //判断有没有超过1分钟
46             $max_time = $redis->lRange($ip,0,0);
47             //判断最后一次访问的时间比对是否超过了1分钟
48             if((time()- $max_time[0]) < 60){
49                 if($len> 10){
50  
51                     echo \'访问超过了限制\';
52                 }else{
53  
54                     $redis->lPush($ip,time());
55                     echo "访问{$len}次<br>";
56                 }
57             }
58         }
59     }
60  
61 }
62 (new api())->test();

 

 

原地址:https://blog.csdn.net/gaoxuaiguoyi/article/details/89462423

 

分类:

技术点:

相关文章: