agyanadda@gmail.com

CodeIgniter 4 Filters

Forms, Sessions and Security 1 min read Updated Dec 3, 2026 Topic 20 of 30

Filters run code before or after a controller — like middleware in other frameworks. Use them for login checks, admin-only pages, CSRF, CORS and more.

Create a filter

php spark make:filter AuthFilter creates a class in app/Filters with two methods:

  • before($request, $arguments = null) — runs before the controller. Return a redirect or response to stop the request.
  • after($request, $response, $arguments = null) — runs after, and can change the response

Register an alias

In app/Config/Filters.php, add it to $aliases: 'auth' => \App\Filters\AuthFilter::class.

Apply the filter

  • On a route: $routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']);
  • On a group: $routes->group('admin', ['filter' => 'auth'], ...)
  • With arguments: ['filter' => 'role:admin'] → $arguments = ['admin']
  • Globally in Filters.php $globals, or by URL pattern in $filters

Built-in filters

csrf, toolbar (debug toolbar), honeypot, invalidchars, secureheaders, cors and more.

Example

Example — Login and role filters PHP
<?php
namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (! session('user_id')) {
            return redirect()->to('login')->with('error', 'Please log in first.');
        }

        // ['filter' => 'auth:admin'] -> $arguments = ['admin']
        if ($arguments && ! in_array(session('role'), $arguments, true)) {
            return redirect()->to('/')->with('error', 'You do not have access.');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    }
}

// app/Config/Filters.php  ->  public array $aliases = [ ..., 'auth' => \App\Filters\AuthFilter::class ];

// app/Config/Routes.php
// $routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']);
// $routes->group('admin', ['filter' => 'auth:admin'], static function ($routes) { ... });

Guests who open /dashboard are sent to /login. Logged-in users without the admin role are sent to the home page when they open any /admin URL.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does a filter's before() do to stop a request?

Exercise 2 True / False

Filter aliases are registered in app/Config/Filters.php.

Exercise 3 Fill in the Blank

Create a filter with php spark make:___ AuthFilter

Frequently Asked Questions

A check in BaseController runs for every controller. A filter can be attached to exactly the routes or groups that need it, can take arguments (like role:admin), and runs before the controller is even created. Filters are the cleaner choice.