01. We created App / Filters Throttle.php a directory file, which is written only have access to 10 times in one minute, if the time exceeds one second to access the code is as follows:
<?php namespace App\Filters; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Config\Services; class Throttle implements FilterInterface { // This is a class for use Trottler applications to achieve rate-limiting examples of public function before (RequestInterface $ Request ) { $throttler = Services::throttler(); // the entire IP address on the site is limited to no more than one request per second IF ( $ Throttler -> Check ( $ Request -> getIPAddress (), 10, MINUTE) === to false ) { return Services :: Response ( ) -> setStatusCode (429 ); } } // temporarily nothing to do public function the After (RequestInterface $ Request , ResponseInterface $ the Response ) { } }
02. We in App / Config / Filters file, write the following code:
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. We write the code for a controller output in the 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)哦,谢谢。