Mogens TrasherDK
Mogens TrasherDK

Reputation: 680

Apache / PHP and dynamic CORS

I'm having a hard time to get around that CORS thing.

I have a javascript sending AJAX Put/Fetch requests to Apache/PHP script.

In this case, for the example, the javascript is running on CodePen, and the Apache/PHP is on a local server.

I'm checking the origin against a list of allowed hosts.

It should be possible to let PHP return headers like:

$headers = getallheaders();

if ( checkorigin($headers['Origin']) === false) $headers['Origin'] = null;

header('Access-Control-Allow-Origin: ' . $headers['Origin']);
header('Access-Control-Allow-Methods: PUT, POST');
header('Access-Control-Allow-Headers: content-type');
header('Access-Control-Allow-Credentials: true');

This doesn't work.

Hard coding https://s.codepen.io into the header does work.

Ideas anyone ?

Solution

Changing from:

header('Access-Control-Allow-Origin: ' . $headers['Origin']);

to:

header('Access-Control-Allow-Origin: ' . "{$_SERVER['HTTP_ORIGIN']}");

did the trick. Thanks to Rohit.007

Upvotes: 0

Views: 548

Answers (1)

Rohit.007
Rohit.007

Reputation: 3502

try

header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");

Upvotes: 1

Related Questions