Controller Filters

    • Restricting areas of your site based upon their Role
    • Perform rate limiting on certain endpoints
    • Display a “Down for Maintenance” page
    • Perform automatic content negotiation
    • and more..

    Filters are simple classes that implement .They contain two methods: before() and after() which hold the code thatwill run before and after the controller respectively. Your class must contain both methodsbut may leave the methods empty if they are not needed. A skeleton filter class looks like:

    From any filter, you can return the object and it will replace the current Request, allowing youto make changes that will still be present when the controller executes.

    Since before filters are executed prior to your controller being executed, you may at times want to stop theactions in the controller from happening. You can do this by passing back anything that is not the request object.This is typically used to perform redirects, like in this example:

    1. public function before(RequestInterface $request)
    2. {
    3. $auth = service('auth');
    4.  
    5. if (! $auth->isLoggedIn())
    6. {
    7. return redirect('login');
    8. }
    9. }

    If a Response instance is returned, the Response will be sent back to the client and script execution will stop.This can be useful for implementing rate limiting for API’s. See app/Filters/Throttle.php for anexample.

    After Filters

    After filters are nearly identical to before filters, except that you can only return the $response object,and you cannot stop script execution. This does allow you to modify the final output, or simply do something withthe final output. This could be used to ensure certain security headers were set the correct way, or to cachethe final output, or even to filter the final output with a bad words filter.

    The array is used to associate a simple name with one or more fully-qualified class names that are thefilters to run:

    1. public $aliases = [
    2. 'csrf' => \CodeIgniter\Filters\CSRF::class
    3. ];

    Aliases are mandatory and if you try to use a full class name later, the system will throw an error. Defining themin this way makes it simple to switch out the class used. Great for when you decided you need to change to adifferent authentication system since you only change the filter’s class and you’re done.

    You can combine multiple filters into one alias, making complex sets of filters simple to apply:

    You should define as many aliases as you need.

    $globals

    The second section allows you to define any filters that should be applied to every request made by the framework.You should take care with how many you use here, since it could have performance implications to have too manyrun on every request. Filters can be specified by adding their alias to either the before or after array:

    1. public $globals = [
    2. 'csrf'
    3. ],
    4. 'after' => []
    5. ];
    1. public $globals = [
    2. 'before' => [
    3. 'csrf' => ['except' => 'api/*']
    4. ],
    5. 'after' => []
    6. ];

    Any place you can use a URI in the filter settings, you can use a regular expression or, like in this example, usean asterisk for a wildcard that will match all characters after that. In this example, any URL’s starting with api/would be exempted from CSRF protection, but the site’s forms would all be protected. If you need to specify multipleURI’s you can use an array of URI patterns:

    You can apply filters to all requests of a certain HTTP method, like POST, GET, PUT, etc. In this array, you wouldspecify the method name in lowercase. It’s value would be an array of filters to run. Unlike the $globals or the properties, these will only run as before filters:

    1. public $methods = [
    2. 'post' => ['foo', 'bar'],
    3. 'get' => ['baz']
    4. ]

    In addition to the standard HTTP methods, this also supports two special cases: ‘cli’, and ‘ajax’. The names areself-explanatory here, but ‘cli’ would apply to all requests that were run from the command line, while ‘ajax’would apply to every AJAX request.

    Note

    The AJAX requests depends on the X-Requested-With header, which in some cases is not sent by default in XHR requests via JavaScript (i.e. fetch). See the section on how to avoid this problem.

    $filters

    1. public filters = [
    2. 'foo' => ['before' => ['admin/*'], 'after' => ['users/*']],
    3. 'bar' => ['before' => ['api/*', 'admin/*']]
    4. ];

    Three filters are bundled with CodeIgniter4: Honeypot, Security, and DebugToolbar.