Share the same Session on Different Domains on the same Server

Asked

Viewed 1,493 times

6

You can share the same session between different domains on the same server?

If possible, what to do to achieve such a feat?

2 answers

2


Alexandre, really this feat is not possible, the session remains active only in the domain that created it, at most what could be done would be to share this session for use in the subdomains of the domain in question.

1

Yes, it is possible

But it involves a lot of code, and solution is not so simple. Two separate issues to solve: allowing session data to be accessible to different "servers", the session ID to reach the two different domains.

Share the session data

PHP session data is usually stored as files in a specific temporary directory. See session_save_path(). If both applications are physically on the same server, a solution is to create a shared folder and call session_save_path() before session_start().

It’s not always possible. Servers in virtual domain schema usually prohibit access to files outside of the configured Docroot, so a common folder is impossible.

Alternative solution is to use a custom handler to read/save session data in a database or a memcached of life, thus escaping the constraints of Docroot.

Share your session ID

Both applications still need to receive the same Session ID. PHP session ids can be passed by cookies or URL. Cookies are restricted to the domain where they were created, and cannot be created "for other domains".

The way is to do that both the domains register the same cookie at the same time. Something like that:

<img src="http://www.dominio1.com/cross_session.php?<?php echo htmlspecialchars(SID); ?>"/>
<img src="http://www.dominio2.com/cross_session.php?<?php echo htmlspecialchars(SID); ?>"/>

And in the archive cross_session.php simply flame session_start() passing SID as argument. This will create the appropriate cookie, and when the guy jumps from one site to another, the session will be waiting for him, transparently.

Caveat emptor

The above code is a minimal example. It works, but it’s ugly. It leaves traces of session Ids in server logs.

Less ugly solution would be to make requests via Javascript/Ajax type POST (to leave no trace) in less obvious filenames (to let the staff incited to futulate your server).

The important thing is that a browser has SID explicitly, and that a browser makes requests in both domains, to create two cookies, one for each domain, with the same SID. The following login page is ideal for doing this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.