I have a very simple PHP file on an Apache server that have to responds to a Ajax request. I am trying to allow CORS but it doesn't work (Firefox console shows: Reason: CORS header 'Access-Control-Allow-Origin' missing).
I try different solutions from this question but it doesn't work. I an not using any framework, only a index.php file on an Apache server.
This code is the simplest that I found but it doesn't work (index.php):
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
echo('CORS activated!!!');
?>
My HTML file:
$.ajax({
type: 'GET',
url: 'http://localhost/index.php',
})
.done(function(data) {
console.log('Do I have CORS?: ' + data);
})
.fail(function() {
alert("Error");
});
Possibility 1: Per MDN, you can't use the wildcard (*) for Access-Control-Allow-Origin if you also use Access-Control-Allow-Credentials.
For requests without credentials, the literal value "*" can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. Attempting to use the wildcard with credentials will result in an error.
<?php
header("Access-Control-Allow-Origin: *"); //Either change this to your domain(s)
header("Access-Control-Allow-Credentials: true"); //Or get rid of this
?>
(The reason is: This combination would allow anyone on the internet to impersonate one of your users by loading your domain in an iframe then manipulating it with JS, completely invisibly.)
It's probably that, but the below might help with testing anyway:
Possibility 2: Your index.php is being cached, so after you made the changes, your browser is still seeing the old version. The 'disable cache' feature in the dev console can be unreliable for some things like iframes and CSS URL resources. Try visiting index.php from a private browsing session, and check what headers are being sent in the dev console.