phpsessioncross-domaincross-server

PHP cross subdomain session for subdomain on different server


I have 3 domains:

  1. member.example.com for centralizer login on SERVER1
  2. news.example.com for news on SERVER1
  3. video.example.com for videos on another server SERVER2

For cross sub domain sessions I'm using:

session_name('example');
session_set_cookie_params(0, '/', '.example.com');
session_start();

When a user logs onto member.example.com, all of the session data is available on news.example.com but not on video.example.com because it is on another server. The session id is the same on all subdomains, but since it's a different physical box, the session file is not there.

I'm looking for the best method to be able to share sessions across subdomains when the subdomains are hosted on different physical servers.

I know the approach of storing the data in a database, but wish to avoid this. I also know I can send encrypted session information in the URL for video.example.com, but I feel it is ugly, and I want to create a clean solution.

After traversing cookies, and other implementations, I explored the following scenario.

In members.example.com after successfully logging in, I tried to create a session for video.example.com by calling a session generation page on video.example.com using cURL. I tried using the following code (and passing the appropriate fields with cURL):

session_name('example');
session_set_cookie_params(0, '/', '.example.com');
session_start();
$_SESSION['id']=$_POST['id'];
$_SESSION['name']=$_POST['name'];
print_r($_SESSION)

In the cURL response I found these variables set for session but unfortunately a new session id was created for the cURL call. I tried to resolve this by the existing session ID, but it did not work.

I am aware of other options, but am specifically interested in this approach.


Solution

  • On both severs session id, session name, cookie params and other session settings must be the same. So you should send session_name(), session_id(), other session params and session data to video server. Then on video you create

    session_name($_POST['name']);
    session_set_cookie_params(0, '/', '.example.com');
    session_id($_POST['id']);
    session_start();
    $_SESSION = array_merge($_SESSION, $_POST['session_data']);
    

    try if it works.