How To Enable CORS in CodeIgniter 4 for REST APIs

CodeIgniter 4 provides several functionality. We can use CodeIgniter 4 to create REST APIs. Inside this article we will see the concept i.e How to enable CORS in CodeIgniter 4 for rest apis. Article contains very classified information

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. It Supports secure cross-origin requests and data transfers between browsers and servers.

Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests.

Learn More -

This article has used CodeIgniter v4.1.5 for demonstration of this article.

Let’s get started.

Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system.

To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 -

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics — Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer -

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

.env Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

Above command will create a copy of env file to .env file.

Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production // Do it to CI_ENVIRONMENT = development

Now application is in development mode.

How To Setup CORS Settings

To setup CORS settings we will create a CodeIgniter filter and then add cors settings to process request.

Open project into terminal and run this spark command.

$ php spark make:filter Cors

This command will create a filter file named Cors.php in /app/Filters folder.

Open Cors.php and write this complete code into it.

<?php namespace App\Filters; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; class Cors implements FilterInterface { /** * Do whatever processing this filter needs to do. * By default it should not return anything during * normal execution. However, when an abnormal state * is found, it should return an instance of * CodeIgniter\HTTP\Response. If it does, script * execution will end and that Response will be * sent back to the client, allowing for error pages, * redirects, etc. * * @param RequestInterface $request * @param array|null $arguments * * @return mixed */ public function before(RequestInterface $request, $arguments = null) { header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: X-API-KEY, Origin,X-Requested-With, Content-Type, Accept, Access-Control-Requested-Method, Authorization"); header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PATCH, PUT, DELETE"); $method = $_SERVER['REQUEST_METHOD']; if($method == "OPTIONS"){ die(); } } /** * Allows After filters to inspect and modify the response * object as needed. This method does not allow any way * to stop execution of other after filters, short of * throwing an Exception or Error. * * @param RequestInterface $request * @param ResponseInterface $response * @param array|null $arguments * * @return mixed */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { // } }

We can see we have added all CORS setting to before() method. This before() method always executes before processing any request.

Now, next we need to load inside application.

Load CORS Filter

Open Filters.php file from /app/Config folder.

Search for $aliases. Add these lines into it.


use App\Filters\Cors;


public $aliases = [ 'csrf' => CSRF::class, 'toolbar' => DebugToolbar::class, 'honeypot' => Honeypot::class,  'cors' => Cors::class,  ];

Search for $globals. Add this line into it.

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

Now, successfully we have the done the CORS setup to CodeIgniter 4 application. You can create rest apis and use anywhere.

We hope this article helped you to learn How to enable CORS in CodeIgniter 4 for rest apis Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on and .

Originally published at on December 30, 2021.




Online Web Tutor is web development community found by Sanjay Kumar. It provides web development course for free worldwide by professionally trained instructors

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Online Web Tutor

Online Web Tutor

Online Web Tutor is web development community found by Sanjay Kumar. It provides web development course for free worldwide by professionally trained instructors

More from Medium

How To Load Database in CodeIgniter 4 Custom Library

XAMPP — MySQL shutdown unexpectedly

How to Create login, register, and logout manually in laravel.

Fastest WordPress hosting service provider is HERE!