I\'m doing a ajax call to my own server on a platform which they set prevent these ajax calls (but I need it to fetch the data from my server to display retrieved data from
It's a really bad idea to use *
, which leaves you wide open to cross site scripting. You basically want your own domain all of the time, scoped to your current SSL settings, and optionally additional domains. You also want them all to be sent as one header. The following will always authorize your own domain in the same SSL scope as the current page, and can optionally also include any number of additional domains. It will send them all as one header, and overwrite the previous one(s) if something else already sent them to avoid any chance of the browser grumbling about multiple access control headers being sent.
class CorsAccessControl
{
private $allowed = array();
/**
* Always adds your own domain with the current ssl settings.
*/
public function __construct()
{
// Add your own domain, with respect to the current SSL settings.
$this->allowed[] = 'http'
. ( ( array_key_exists( 'HTTPS', $_SERVER )
&& $_SERVER['HTTPS']
&& strtolower( $_SERVER['HTTPS'] ) !== 'off' )
? 's'
: null )
. '://' . $_SERVER['HTTP_HOST'];
}
/**
* Optionally add additional domains. Each is only added one time.
*/
public function add($domain)
{
if ( !in_array( $domain, $this->allowed )
{
$this->allowed[] = $domain;
}
/**
* Send 'em all as one header so no browsers grumble about it.
*/
public function send()
{
$domains = implode( ', ', $this->allowed );
header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
}
}
Usage:
$cors = new CorsAccessControl();
// If you are only authorizing your own domain:
$cors->send();
// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
$cors->add($domain);
}
$cors->send();
You get the idea.