Cross domain PHP Sessions

You can’t set cookies cross domain by default. I believe, you can set up a P3P file(s) to enable it. http://p3ptoolbox.org/guide/section4.shtml#IVd
I haven’t done this myself, so I don’t know how much of the browsers implement it or if it even works that way.

Virb looks like it’s just using JavaScript. It has an AJAX library, that makes a JSON-P request to the virb server if no session cookie is set. (first load of Firefox you can see this in Firebug) The JSON response just lets the page know if the user is logged in or not, and updates the portions of the page that need to reflect user status.

So what’s happening is the page embeds some JS from virb.com. Since the domain is virb.com it cookies set to virb.com are sent to the server. The server then responds with the result of the cookie to the external site.

In the case of virb, which won’t work properly without JS, I think thats a good option. However, you could do the same with HTTP Redirects.

If the HTTP Host is not the main domain (example.com):

if (!$_COOKIE['sessionid'] && $_SERVER['HTTP_HOST'] != 'example.com') {
// redirect to your main site
header('Location: http://example.com');
}

On the main site, set the cookie, and send the user back to the external domain (domain.com) passing the session id in the Location.

header('Location: http://domain.com.com?sessid='.urlencode($_COOKIE['sessionid']));

The final bit is to redirect back to the page you were on now that you have the same session going.

setCookie(...); // sessid in $_GET['sessid']
header('Location: http://domain.com/'); 

Note, in actuality you can send the page you’re currently on back to example.com in the first step, so you can redirect back to it later.

Since you’re just using headers (you don’t need to output content) and in most cases HTTP/1.1 so you’ll be on the same TCP socket I think it’s pretty efficient and will be more supported then the JavaScript option.

Edit: don’t forget to set the cookie when you get back to external domain.

Last step is optional but it keeps the sessid from being in a URL. Which is more of a security issue then keeping it in HTTP headers.

Leave a Comment