I have a (.NET) application that calls a PHP app, residing on a different subdomain, via AJAX.
To break down the problem, I wrote a simple test script:
<?php
setcookie('test', '1234', time()+60*60*24*30, '/', '.mydomain.com');
header('Access-Control-Allow-Origin: *');
echo 'Cookies: '; print_r($_COOKIE);
?>
If called by direct request, the script behaves as expected – spits out an array with all the .mydomain.com cookies and sets the ‘test’ cookie.
Let’s assume that I’m calling app2.mydomain.com/cookieTest.php from app1.mydomain.com/page1.aspx.
app1 is running on an IIS server, app2 on a Nginx (Linux) server.
So, on app1.mydomain.com/page1.aspx I run this JS:
$.ajax({
'url' : 'https://app2.mydomain.com/cookieTest.php',
'success': function(r){
$('#container').html(r);
}
});
The script returns an empty array for $_COOKIE and attempts to set a cookie but it fails.
The response header looks like this:
Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:app2.mydomain.com
Origin:https://app1.mydomain.com
Referer:https://app1.mydomain.com/page1.aspx
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
Response Headers
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Type:text/html
Date:Fri, 21 Sep 2012 20:54:12 GMT
Server:nginx
Set-Cookie:test=1234; expires=Sun, 21-Oct-2012 20:54:12 GMT; path=/; domain=.mydomain.com
Transfer-Encoding:chunked
(note the set-cookie, which the browser ignores)
What can be going wrong here?
After some more research ( http://www.bradchen.com/node/28 and https://developer.mozilla.org/en-US/docs/HTTP_access_control ) I realized that this is not achievable directly, but there are workarounds for both ways (getting and setting).
It’s actually pretty easy: you can get the PHP app to read cookie values by passing a session ID or whatever else is in the cookies that we want to pass, and setting new cookies by parsing PHP’s headers_list() and creating a JS that lets the browser set those cookies.