Skip to content

Instantly share code, notes, and snippets.

@feulf
Last active July 27, 2022 11:15
Show Gist options
  • Save feulf/4587709 to your computer and use it in GitHub Desktop.
Save feulf/4587709 to your computer and use it in GitHub Desktop.
Keep the same PHP session between different domains

a simple idea is to force the session_id between the domains with an ajax call or an hidden iframe.

The concept is simple, you have [A,B,C] domains, where you create a script sid.php:

<?php session_id( $_GET['sid'] );

and a script sid_update.php that you have to place inside the PHP code of the front controller:

    
    <?php
    // start the session
    session_start();
    // get the session id
    $sid = session_id();
    // url of all domains
    $domains = ['A','B','C'];
    // this domain, you may want to set this manually
    $url = $_SERVER['SERVER_NAME'];

    // execute this script only once
    if( isset($_SESSION['sid_updated']) && true === $_SESSION['sid_updated'] ){
      foreach( $domains as $domain ){
        // update all domains except the one we are now
        if( $domain != $url ){
          // print an hidden iframe
          echo "<iframe src=\"{$domain}?sid={$sid}\" style="position:absolute;top:-1000;"></script>";
        }
     }
     $_SESSION['sid_updated'] = true;
   }

An AJAX call it could be better then the iframe, up to you to implement a better solution.

Note

This solution is not safe! If you have a good solution to improve the security of it, please update this GIST.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment