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
