The Problem
The problem I was having was due to a setting in my Apache config file which looked like this:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
In order to solve my particular problem I simple removed / commented out the above code as it was overriding the headers I sent from PHP.
My implemented solution was then quite simple. In the following example we'll assume that I am making a call from one.example.com
(the main website) to two.example.com
(a sub-site).
Kohana / PHP
In my PHP I set the following headers, I've chosen to do this in my parent Controller. You could create your own Cors class or helper if you prefer. Basically you don't want to have this code duplicated hundreds of times throughout your project.
$this->response->headers('Access-Control-Allow-Origin', 'http://one.example.com');
$this->response->headers('Access-Control-Allow-Credentials', 'true');
$this->response->headers('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
JavaScript / jQuery
In my $.ajax()
requests I then have to make sure to set the xhrFields.withCredentials
property to true
.
$.ajax({
url: 'two.example.com',
xhrFields: {
withCredentials: true
}
});
Or I could set it globally for all ajax requests like so:
$(document).ajaxSend(function (event, xhr, settings) {
settings.xhrFields = {
withCredentials: true
};
});
For more information check the $.ajax
documentation: http://api.jquery.com/jQuery.ajax/
Further Reading
For further information checkout the following resources: