本文主要是介绍ThinkPHP5.1 限制接口高频恶意请求,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
创建一个中间件
php think make:middleware Api
中间件内添加
/*** 次数限制 用于限制一天内有N次机会,或X秒内有N次机会 优化后使用加法,逻辑更加通畅
// * @param $unique_id 唯一标识(用户ID或手机号)* @param $numberoftimes 最大次数N* @param $timespant 时间间隔(字符串oneday一天或者过期秒数X)* @param $verification 是否只做验证false|true* @return bool|mixed*/function limitoftimes($numberoftimes=10,$timespant="oneday",$verification=false){$cacheneme = request()->url().$numberoftimes;$nowtimes = cache($cacheneme);//获取缓存中的当前次数if($nowtimes>=$numberoftimes)return false;if($verification)return true;if($timespant==="oneday"){$expires_in = strtotime(date('Y-m-d',strtotime('+1 day'))) - time();}else{$expires_inname = $cacheneme."-".$timespant;//设置时间缓存名称
这篇关于ThinkPHP5.1 限制接口高频恶意请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!