Throttler is used to limit some actions for number of times for given time period.
for example, if you want to limit login attempt for 4 times in 1 minute, then you can use Throttler. And you don’t need to write any logic to handle this. Throttler will do this internally.
this is how my LoginController will look like if i want to achieve this:
<?php namespace App\Controllers;class LoginController extends BaseController{public function index(){return view('welcome_message');}//--------------------------------------------------------------------//this will be a post method sent from login form.public function doLogin(){$throttler = \Config\Services::throttler();$allowed = $throttler->check('login', 4, MINUTE);if($allowed) {//do your login process}else {//return error or do nothing according to your need.}}}
And this will limit users to login 4 times in a minute.
$throttler->check('login', 4, MINUTE);
in this function
login
is identifier or you can say key.4
is limit (how much operation we want to perform)MINUTE
is constant in CI4 which is equivalent to 60
, and here 60
is seconds. So instead of MINUTE
you can pass 60
or 45
.Throttler
class does not provide system wide functionality to handle rate limiting, but we can achieve this by using Filters in Codeigniter 4. I have explained everything in this video. So checkit out to understand about Controller filters in Codeigniter 4.
So we will restrict requests from same IP to allow 1 request per 1 second. For this first of all create Filter. I will name my filter as IPThrottler
. so create new file named IPThrottler.php
in app/Filters
directory of your Codeigniter 4 project.
IPThrottler.php
After creating filter class we have to create an aliases for our newly created filter. Open /app/Config/Filters.php
file and declare aliase like below
public $aliases = [...'ip_throttle' => \App\Filters\IPThrottler::class,];public $globals = ['before' => [...'ip_throttle'],'after' => [...],];public $methods = ['post' => ['CSRF', 'ip_throttle']];
After doing above chnages now try to open any page of your Codeigniter 4 project and reload page again and again and you will notice that you will get error after reloading 4 times.
Quick Links
Legal Stuff
Social Media