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

Laravel Image Conversion to WebP in the fly Laravel

Image Conversion to WebP in the fly Laravel

February 22, 2024March 16, 2024

Are you looking to optimize your web application’s image handling and delivery speed? In the world of web development Image Conversion to WebP in the fly Laravel is key, and one of the ways to achieve faster loading times for images is by using the WebP format. Laravel, a popular…

Read More
Php How to create migration in laravel

How to Create Migration in Laravel ?

February 15, 2022February 22, 2022

Migrations are used to manage the version control among the developers so that they can sync database schema to each other. Laravel itself provides database migration capabilities to manage database schema updates like create table, alter, modify, drop etc. Main advantage of migrations are to maintain the same schema across…

Read More
Laravel get single column value in laravel

How to get single column value in laravel ?

November 14, 2023March 16, 2024

In this guide, we’ll dive into get single column value in Laravel Eloquent ORM. In Laravel development, optimizing database queries is pivotal for creating efficient and high-performance applications. This technique is valuable for extracting targeted data from your database, enhancing the precision and speed of your application. To illustrate get…

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

  • 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

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version