Jump to content

Cross-Domain Ajax, Multiple Site Syntax Issues


LLLLLLL

Recommended Posts

What is the correct syntax for listing multiple domains to be allowed for cross-domain AJAX calls? My code does this:

 

<?php
header("Access-Control-Allow-Origin: http://website.com");

 

This works when website.com is the caller, but not when www.website.com is the caller. So I tried:

 

<?php
header("Access-Control-Allow-Origin: http://website.com http://www.website.com");

 

... and...

 

<?php
header("Access-Control-Allow-Origin: http://website.com, http://www.website.com");

 

But these things don't work. When I say they don't work, I mean that neither website.com nor www.website.com will be able to make the call with those configurations. So right now the only option is to put * and allow everything. I don't want to do that.

 

Is there another header directive or something that I need? I saw something about Access-Control-Allow-Headers: X-Requested-With but that didn't work either.

I don't have HTTP_ORIGIN in the requests. I've tested on my server and a couple customers. This won't work as a solution.

 

So two questions:

1) What is the expected format to list domains? Comma-separated? Space-separated? Some server setting that determines the separation? It should work.

2) Can I put multiple headers like this? Is it expected and/or good practice?

 

 

<?php

header("Access-Control-Allow-Origin: http://website.com");

header("Access-Control-Allow-Origin: http://www.website.com");

The spec says space separated. Whether browsers allow it or not I don't know, I have not really dealt with such stuff yet.

 

You should have the origin header value somewhere. It's a required header as part of the CORS stuff. If your using a CGI setup you may need to configure the server to forward that header along to PHP.

 

  • 4 weeks later...

try this

 

 

<?php
  $http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://www.domain1.com" || $http_origin == "http://www.domain2.com" || $http_origin == "http://www.domain3.info")
{ 
  header('Access-Control-Allow-Origin: *');
}
?>

$_SERVER['HTTP_REFERER']; You can do something like a preg_match() to check your domains against the HTTP_REFERER and see if you want to send the extra header() to allow cross-domain ajax requests. I'm fairly sure the HTTP_REFERER will do what you are looking for in this case, but lack of sleep may have me convinced of things that aren't necessarily true. I may eventually implement something along these lines for my own purposes, so if it works or you find a better way, don't forget to drop back by here and let me know how it turns out.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.