Middleware and Filters

📘 CodeIgniter 👁 37 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Middleware and Filters in CodeIgniter (CodeIgniter 4)

In CodeIgniter 4, Filters act like middleware. They allow you to run code before or after a request, commonly used for authentication, authorization, CSRF protection, and request modification.


1. What Are Filters?

  • Code executed before or after a controller runs

  • Used to protect routes

  • Similar to middleware in Laravel


2. Filter Location

app/Filters/

3. Creating a Filter

Use Spark CLI:

php spark make:filter Auth

This creates:

app/Filters/Auth.php

4. Filter Example (Authentication)

namespace App\Filters; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Filters\FilterInterface; class Auth implements FilterInterface { public function before(RequestInterface $request, $arguments = null) { if (! session()->get('logged_in')) { return redirect()->to('/login'); } } public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { // Optional post-processing } }

5. Registering Filters

File:

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

6. Applying Filters to Routes

Single Route

$routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']);

Route Group

$routes->group('admin', ['filter' => 'auth'], function($routes) { $routes->get('dashboard', 'Admin::dashboard'); });

7. Global Filters

Apply to all requests.

public $globals = [ 'before' => [ 'csrf', ], 'after' => [ 'toolbar', ], ];

8. Filter Arguments

$routes->get('admin', 'Admin::index', ['filter' => 'role:admin']);

Filter:

public function before(RequestInterface $request, $arguments = null) { if ($arguments[0] !== session()->get('role')) { return redirect()->back(); } }

9. Built-in Filters

FilterPurpose
csrfCSRF protection
toolbarDebug toolbar
honeypotSpam protection
forcehttpsForce HTTPS

10. API Authentication Filter Example

public function before(RequestInterface $request, $args = null) { $token = $request->getHeaderLine('Authorization'); if (! $token) { return service('response') ->setJSON(['error' => 'Unauthorized']) ->setStatusCode(401); } }

11. Best Practices

✅ Use filters for authentication & authorization
✅ Keep filters lightweight
✅ Apply filters at route-level
❌ Avoid heavy logic in filters


Summary

  • Filters = Middleware in CI4

  • Used before/after requests

  • Protect routes & APIs

  • Centralized request control


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes