Sharing PHP session id between different domains

In this post we will create a basic system for sharing a session id between multiple domains.
This allows for single sign on / cart sharing etc.


The way we accomplish this is by loading a small image from the other domains. The URL to this image will contain our session id so the other site can retrieve this and set it's session_id to match.

Note: This will only work if the sites all share the same session storage.

There are only 2x files required.
All the sites will contain the same 2x files.

The first will create the image links containing the session ID, and the second will retrieve this session id, change it's id to match and then show a tiny blank image.

test.php
<?php
$sites = array('www.site1.com', 'www.site2.com');

session_start();
if (!isset($_SESSION['sso_sites'])) {
    foreach($sites as $site) {
        if ($site != $_SERVER['HTTP_HOST']) {
            $_SESSION['sso_sites'][] = $site;
        }
    }
}
?>

<html>
<head></head>

<body>
My Session ID: <?php echo(session_id()); ?>

<?php
foreach ($_SESSION['sso_sites'] as $site) {
    $url = sprintf('http://%s/sso.php?i=%s', $site, session_id());
    echo('<img src="'.$url.'" style="border:0;" alt=""/>');
}
?>

</body>
</html>

You will need to change the $sites array to match the sites you want to have all share the same session_id.

We set  a session variable to hold all the sites that need their session_id changed. Once they have changed, they will then remove themselves from this array and therefore no image will be loaded for them.

sso.php
<?php
session_start();

$session_id = trim($_GET['i']);
if ($session_id != session_id()) {
    session_destroy();
    session_id($session_id);
    session_start();
}

if (isset($_SESSION['sso_sites'])) {
    if (($key = array_search($_SERVER['HTTP_HOST'], $_SESSION['sso_sites'])) !== false) {
        unset($_SESSION['sso_sites'][$key]);
    }
}

header('Content-Type: image/gif');
echo base64_decode('R0lGODlhAQABAJAAAP8AAAAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==');

This code simply retrieves the session id, checks if it is different to it's current session_id and then set's it if it is.

Once we are using the same session data, we can remove our site from 'sso_sites' so it no longer will be set.

Finally it outputs a tiny blank 1px by 1px image to keep the browser happy.

If you upload this code to each site and visit www.site1.com/test.php and see it give you your session id. Now, if you visit www.site2.com/test.php you should also see it give you the same session id.

Congrats, both sites are now using the same session data :)

Note: There is no security considerations in this code.

Discussion

Support

Check out the Supporter Perks

Follow