Search

How to CORS in CodeIgniter ?

  • Share this:
post-title

Learn what CORS is, how to configure it in CodeIgniter, and the relevant configuration options to expose your application for cross-origin requests securely in CodeIgniter.

Have you ever put JavaScript code on a website that was supposed to fetch data from a remote server, only to realize that it didn’t work? Then you probably looked at your browser’s developer tools and noticed an error message referring to CORS or the same-origin policy. 

This article is for you if the remote server is under your control and its server-side code is a CodeIgniter application. To fix your issues, we’ll walk through the process of setting up CORS in CodeIgniter step by step.

What Is CORS?

CORS is a security feature to prevent unauthorized access to server resources. It stands for Cross-Origin Resource Sharing

CORS is a mechanism based on HTTP headers that specify exceptions to the same-origin policy and allow cross-origin requests under specific circumstances. A cross-origin request is a website at one origin, such as https://sample.com, accessing a resource on a different origin, such as https://sample.net. 

Why do we need cors ?

Because it’s a security feature, your default strategy should be to enable CORS only when you’re sure that you need it, and only where you need it. First of all, not every cross-origin request requires CORS. because embedding an image, media file, IFrame, CSS stylesheet, or JavaScript library from another domain isn’t subject to the same-origin policy.

What is required to enable CORS?

The simplest method to enable CORS is to add Access-Control-Allow-Origin:* to the response header from WEB servers, which allows CORS from any source. If you want to limit the source, you should specify the domain in the configuration such as Access-Control-Allow-Origin: https://sample.com. You should note that a domain has to be specified if an http request includes cookie information.

This is a Short Snippet for Code Igniter to Enable CORS on Controller. 

public function __construct()
{
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    parent::__construct();
}
About author
Hi ! I'm Adil Khan Ajad from india and i have 8+ years experience in software. i'm working in stack solution as ceo and founder of stackoverlode.
View all posts (3)