Laravel5.0 限制請求頻率中介軟體

xiaoxiang發表於2019-10-31

相關函式
部落格:Laravel 返回 JSON 格式函式

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;
use App\Libs\Xres;

class ThrottleRequests {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $unique = $request->getClientIp() . $request->getRequestUri();
        if (Cache::has('ip_list')) {
            $ip_list = Cache::get('ip_list');
        } else {
            $ip_list = array();
        }
        $index = array_search($unique, array_column($ip_list, 'ip'));
        if (false === $index) {
            array_push($ip_list, ['ip' => $unique, 'time' => $this->time()]);
            Cache::put('ip_list', $ip_list, 1440);
        } else {
            $gap = $this->time() - $ip_list[$index]['time'];
            $ip_list[$index]['time'] = $this->time();
            Cache::put('ip_list', $ip_list, 1440);
            if ($gap < 1000) {
                return Xres::error("請求頻率過快", 200);
            }
        }
        return $next($request);
    }

    private function time(){
        return (int)(microtime(true)*1000);
    }
}

相關文章