Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks

How to enable cors in web api php or laravel?

Aman Jain, August 27, 2021August 20, 2022

Cross-Origin Resource Sharing (CORS) is mechanism which allow browser to share the resources between the other domain or port. if the cors is disabled in api or server then other domain can’t access the apis and resource of server.

Example: if a server A wants to access the apis of server B then its impossible until cors is not enable on server B. you will get an error.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource Reason: CORS header ‘Access-Control-Allow-Origin’ missing

how to enable cors in php?

function cors() {
    
    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
        // you want to allow, and if so:
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    }
    
    echo "You have CORS!";
}

you can call cors function in header file or in the file which is includes in all files of your project.

How to enable cors in laravel?

  1. Create a middleware using the artisan command or manually in Http/middleware folder
php artisan make:middleware Cors

or you can also create a file in Cors.php in Http/middleware folder and edit the file

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
         ->header("Access-Control-Allow-Origin", "{$_SERVER['HTTP_ORIGIN']}")
        ->header('Access-Control-Allow-Credentials','true')
        ->header('Access-Control-Max-Age', '86400');  ;

    }
}

2. Add the middleware to Http/Kernel.php in $routeMiddleware

protected $routeMiddleware = [
        ......
        'throttle'      => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'cors'          => \App\Http\Middleware\Cors::class, //Cors added
    ];

So, you can use it in your routes with the cors name:

Route::group(['namespace' => 'User', 'middleware' => ['cors'], 'prefix' => 'user'], function () {

});

Laravel cors using the package:

you can also use the package to enable the cors in laravel

https://github.com/fruitcake/laravel-cors

Enable cors plugin in chrome or any browser

We can also disable the security of cors in browser using the chrome extension

https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en

hence, this will disable the cors in browser but it’s an temporary solution for cors.

Related

Php Laravel Softwares

Post navigation

Previous post
Next post

Related Posts

Php How to create logs file in laravel

How to create logs file in laravel 8 / 9 ?

May 12, 2022May 12, 2022

In this article i will show you to use and create logs file in laravel. Logging is an important aspect when you want to debug your application or you want to monitor the user activities on the application. Laravel itself provides a robust library to create logging on daily basis,…

Read More
Php How to Get Only Soft Deleted Records in Laravel 9

How to Get Only Soft Deleted Records in Laravel 9 ?

June 20, 2022June 20, 2022

In this article we will learn to get only soft deleted records in Laravel. In our recent article Use Soft Delete to Temporary (Trash) Delete the Records in Laravel 9 we learnt to delete the file without actually deleting from database and sometimes we want to show only that records…

Read More

Break and Continue statements

July 18, 2021July 18, 2021

Break and continue statements are used to change the flow of program. lets see the difference and usage of both. Break as the name implies it terminate the current loop and execute the next line of code. Continue do not terminate the loop rather then it skip the current iteration…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version