CodeIgniter 4 Filters - Complete Guide

CodeIgniter 4 Filters: A Complete Guide

Filters in CodeIgniter 4 allow you to process HTTP requests before reaching the controller and responses before being sent to the client.

What are Filters in CodeIgniter?

Filters act as middleware and help in:

  • ✅ Authentication & Authorization
  • ✅ Input Validation
  • ✅ Logging & Monitoring
  • ✅ CORS (Cross-Origin Resource Sharing)
  • ✅ Custom Request Handling

How to Create and Use Filters?

Step 1: Create a Filter

Navigate to app/Filters/ and create a new file AuthFilter.php:


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

class AuthFilter 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)
    {
        // After filter logic (if needed)
    }
}
    

Step 2: Register the Filter

Open app/Config/Filters.php and register the filter:


namespace Config;
use CodeIgniter\Config\BaseConfig;

class Filters extends BaseConfig
{
    public $aliases = [
        'auth' => \App\Filters\AuthFilter::class, // Register filter
    ];
}
    

Step 3: Applying Filters

You can apply filters globally, per route, per method, or per controller.

Global Filter

Apply a filter to all requests in app/Config/Filters.php:


public $globals = [
    'before' => ['auth'], // Runs before every request
    'after'  => [],
];
    

Route-Based Filter

Apply filters to specific routes in app/Config/Routes.php:


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

Method-Based Filter

Apply filters to specific HTTP methods:


public $methods = [
    'post' => ['auth'],  // Runs only on POST requests
];
    

Controller-Based Filter

Apply filters to specific controllers:


public $filters = [
    'auth' => ['before' => ['DashboardController', 'ProfileController']],
];
    

Practical Examples of Filters

Admin Authentication Filter


class AdminFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (!session()->get('is_admin')) {
            return redirect()->to('/not-authorized');
        }
    }
}
    

CORS Filter

Allow API requests from other domains.


class CorsFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
    }
}
    

Conclusion

Filters in CodeIgniter 4 enhance security and simplify request handling. Use them to implement authentication, logging, and security checks efficiently.

🚀 Start implementing filters in your CodeIgniter 4 project today!

💬 Have Questions?

Drop your queries in the comments! 😊

Comments

Popular posts from this blog

CSS Animations and Transitions

Enhancing User Experience with Bootstrap’s JavaScript Components: A Practical Guide

Creating Stunning Landing Pages with Bootstrap: Tips and Best Practices