0

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");
});
Roby Sottini
  • 2,117
  • 6
  • 48
  • 88
  • 1
    No visible reason why this should not work. Do you have proper PHP error reporting enabled? What do you see when you inspect the request in your browser dev tools, network panel? Do you see the response headers there? Does the response body contain any error messages? – CBroe Sep 29 '21 at 12:08
  • Is https://bugs.chromium.org/p/chromium/issues/detail?id=67743 related? – Nico Haase Sep 29 '21 at 12:22
  • This script does not tell apart pre-flight and response ...just alike the canned answer to it... simply change it to: `header("Access-Control-Allow-Origin: http://localhost");`. Case closed. – Martin Zeitler Sep 29 '21 at 12:25

1 Answers1

1

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.

Dev console HTTP Headers

Michael G
  • 458
  • 2
  • 9