Preserving session variables across different domains

It's late to answer this question but as I have faced this problem and could not find the solution even after tens of hours and searching google, stackoverflow all over but yet no success. But now finally I have figured out the problem and the solution for it.

SERVER SIDE

For Cross-Domain PHP Sessions, we need to do following things

Step 1

First of all, we need to set these lines in .htAccess in our main domain where the php receives the request

SetEnvIf Origin ^(http?://m\.example\.com(?::\d{1,5})?)$   CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{CORS_ALLOW_ORIGIN}e   env=CORS_ALLOW_ORIGIN
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Allow-Credentials true
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

These above lines tells to allow requests from http://m.example.com only. Note that I have set http. You can set https if you have SSL Connection.

Step 2

You must allow PHP to share same sessions for different subdomains before session_start()

ini_set('session.cookie_domain', '.example.com');
session_start();

If you have access to php.ini then set it once there then you won't need to set above lines in your PHP Files.

CLIENT SIDE

And last, you must tell the Browser to make request with Cross-Domain. As in JQuery

$(document).ready(function()
{
  $.ajaxSetup({
    crossDomain: true,
    xhrFields: {
        withCredentials: true
    }
  });
});

Cross-domain session ids

Session ids are passed around using cookies by default. Since your websites are on different domains the session cookie does not transfer over, so that's one thing that prevents cross-domain sessions from working.

One technique to have the session ids transfer over is to append them to the query string of all your requests (PHP even has some degree of built-in support for this). However, this way of doing things has many drawbacks -- the most important being that people copy/paste URLs all the time, with all that implies about revealing valid and reusing invalid session ids -- and therefore is not recommended.

A much better approach would be to use Javascript to make cross-domain requests across all of the interested domains (which would need to be cooperating in this of course). This way you can seamlessly transfer your session id across as many servers as you need to.

Shared session data

Even if the cookie were not a problem, you would need to have the session data on some storage commonly accessible by all your servers. The default storage is the local filesystem, so again this is something that needs to change if you want cross-domain sessions.

A simple solution to this problem would be to use a custom session handler that stores the data on a database or other globally accessible store.

Tags:

Php