How To Enable CORS in CodeIgniter 4 for REST APIs

Reading Time: 6 minutes
18,410 Views

Cross-Origin Resource Sharing (CORS) is an important issue when developing RESTful APIs since it determines which domains can access your API services. Enabling CORS in CodeIgniter 4 entails configuring your application to accept requests from specific origins. We will walk you through the process of activating CORS in CodeIgniter 4 to allow secure and restricted access to your REST APIs.

CORS is a complicated topic, but with the appropriate configuration, you can keep your API secure while allowing authorised domains to access your services. In this article, we’ll go over the procedures to enable CORS, explain the important ideas, and show you how to configure CORS properly in your CodeIgniter 4 project.

Read More: How To Create CodeIgniter 4 Custom Library Tutorial

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

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.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

cp env .env

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.

What is CORS (Cross-Origin Resource Sharing)?

CORS, which stands for Cross-Origin Resource Sharing, is a security mechanism built into web browsers that allows web page access to resources from various domains to be controlled.

It’s a method that permits or prevents web applications operating on one origin (domain) from requesting and accessing resources hosted on another. This is an important security precaution to prevent unauthorised access to resources and data.

Read More: CodeIgniter 4 Form Validation Library Example Tutorial

CORS implementation in CodeIgniter, a popular PHP framework for building web applications, often entails enabling or blocking cross-origin access to resources on your web server. The following is how CORS works in CodeIgniter:

Step #1: How To Setup CORS Settings in CodeIgniter

To setup CORS settings we will create a CodeIgniter filter and then add cors settings there 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)
    {
        //
    }
}

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

Now, next you need to load inside application.

Step #2: How To Register CORS Filter To Application

Open Filters.php file from /app/Config folder. Search for $aliases. Add these lines into it.

Load

use App\Filters\Cors;

Use

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

Read More: CodeIgniter 4 How to Work with Redirection Tutorial

Search for $globals. Add this line into it.

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

Once, you do all above settings. Automatically CORS policy will be applied to each and every request inside your application.

That’s it.

We hope this article helped you to learn about How To Enable CORS in CodeIgniter 4 for REST APIs in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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 Twitter and Facebook.