Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

header('Access-Control-Allow-Origin: *'); Not allowing CORS request

Tags:

php

cors

I have a PHP file which generates a JSON document.

I've set the header as follows but am still getting an error.

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

Error message:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://mysubdomain.mydomain.com' is therefore not allowed access.

I've tried explictly allowing mysubdomain.mydomain.com using

header('Access-Control-Allow-Origin: https://mysubdomain.mydomain.com');

But I still get the error.

like image 776
Luke Avatar asked Nov 25 '13 10:11

Luke


People also ask

How do I fix CORS header Access-Control allow Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

How do you fix CORS origin error?

To get rid of a CORS error, you can download a browser extension like CORS Unblock ↗. The extension appends Access-Control-Allow-Origin: * to every HTTP response when it is enabled. It can also add custom Access-Control-Allow-Origin and Access-Control-Allow-Methods headers to the responses.

How do I unblock a CORS request?

Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature.


2 Answers

It doesn't look there is anything wrong with the code that sets the header, but you may want to check if the header is actually being set. Use curl -i http://yourapp to check the response headers being sent to debug it. Alternatively, you can use the network tab in Google Chrome's web inspector, or the Network tool in Firefox's Web Developer tools.

like image 161
Munim Avatar answered Oct 27 '22 21:10

Munim


with htaccess file you can try to set :

Header always set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, PATCH,DELETE"
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Headers "content-type,Authorization,Cache-Control,X-Requested-With, X-XSRF-TOKEN"

Or with PHP:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, PATCH, DELETE');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, Content-Type, x-xsrf-token, x_csrftoken, Cache-Control, X-Requested-With');
like image 4
bharat Avatar answered Oct 27 '22 20:10

bharat