01.我們在App/Filters目錄中創建一個Throttle.php文件,其中寫的是1分鍾內只能訪問10次,如果超出了1秒才能訪問一次,代碼如下:
<?php namespace App\Filters; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Config\Services; class Throttle implements FilterInterface { //這是一個為應用程序使用 Trottler 類來實現速率限制的實例 public function before(RequestInterface $request) { $throttler = Services::throttler(); // 在整個站點上將IP地址限制為每秒不超過1個請求 if ($throttler->check($request->getIPAddress(), 10, MINUTE) === false) { return Services::response()->setStatusCode(429); } } //暫時無事可做 public function after(RequestInterface $request, ResponseInterface $response) { } }
02.我們在App/Config/Filters文件中,寫入以下代碼:
public $aliases = [ 'csrf' => \CodeIgniter\Filters\CSRF::class, 'toolbar' => \CodeIgniter\Filters\DebugToolbar::class, 'honeypot' => \CodeIgniter\Filters\Honeypot::class, 'throttle' => \App\Filters\Throttle::class, ];
public $methods = [ 'post' => ['throttle', 'CSRF'], 'get' => ['throttle'], ];
03. 我們在controller控制器中寫入一段輸出的代碼
<?php namespace App\Controllers; class Hello extends BaseController { //http://127.0.0.1/CI4/public/index.php/hello/ function __construct() { } public function index() { echo '青青子衿悠悠我心' . rand(100, 999); } //-------------------------------------------------------------------- }
04.打開瀏覽器,我們瀏覽器訪問http://127.0.0.1/CI4/public/index.php/hello/,效果如下
05.我們1分鍾超過10次訪問http://127.0.0.1/CI4/public/index.php/hello/之后,會發現瀏覽器無法顯示。需要等2秒再訪問,這樣就很完美的起到了限制IP頻繁訪問的作用了。
原創不易,如果您認為這篇文章有價值,認同作者的付出,可以微信二維碼打賞任意金額給作者(微信號:382477247)哦,謝謝。