enable cors with php code example
Example 1: php access origin
<?php
header("Access-Control-Allow-Origin: *");
Example 2: php strict-origin-when-cross-origin
header("Access-Control-Allow-Origin: *");
Example 3: php header allow cross origin
function cors() {
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
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!";
}
Example 4: cross origin even with allow header
header('Access-Control-Allow-Origin: http://localhost:8100');
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
header ("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header ("Access-Control-Allow-Headers: Content-Type, Authorization, Accept, Accept-Language, X-Authorization");
header('Access-Control-Max-Age: 86400');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header("HTTP/1.1 200 OK");
return;
}
Example 5: Access to XMLHttpRequest at 'http://localhost/MySQL_pracs/InsertUser.php' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
//Access to XMLHttpRequest at 'http://localhost/[api path].php' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
//The error is simply saying that "Content-Type" is missing from "Access-Control-Allow-Headers".
//Therefore we need to add "Content-Type" to "Access-Control-Allow-Headers".
<?php
header('Access-Control-Allow-Headers: Content-Type');
-----
?>
Example 6: laravel Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on
Step 1 : Create Cors middleware.
php artisan make:middleware Cors
Step 2 : Add below lines in handle function before return.
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Authorization, Origin');
header('Access-Control-Allow-Methods: POST, PUT');
Step 3 : Register the middileware in app/Http/Kernel.php file
Add below line in $middleware array
\App\Http\Middleware\Cors::class,
Step 4 : Now we have to call the middleware in app/Http/Kernel.php file
Add below line in $routeMiddleware array
'cors' => \App\Http\Middleware\Cors::class,
Using the * works rather than the host origin. Was missing the Cors.php middleware in the array as well