Share the Same Session in Different Domains on the Same Server

4

Is it possible to share the same session between different domains on the same server?

If at all possible, what can be done to achieve this?

    
asked by anonymous 16.10.2015 / 07:51

2 answers

2

Alexander, 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 subdomains of the domain in question.

    
16.10.2015 / 21:58
1

Yes, it is possible

But it involves a bit of code, and solution is not that simple. Two separate issues to resolve: allow session data to be accessible to different "servers", session ID to reach two different domains.

Share session data

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

It is not always possible. Servers in virtual domain schemas generally prohibit access to files outside the configured DocRoot, so a common folder is impossible.

Workaround is to use a custom handler to read / write data session or a memcached of life, thus escaping the constraints of DocRoot.

Share session ID

It is still necessary that both applications 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 can not be created "for other domains".

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

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

And in the file cross_session.php simply call session_start() passing the 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 in a transparent way.

Caveat emptor

The code above is a minimal example. It works, but it's ugly. Leave traces of session IDs in server logs.

A less ugly solution would be to make via JavaScript / Ajax POST-type requests (not to leave a trace) in less obvious file names (to let staff incite you to overpower your server).

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

    
17.03.2016 / 19:22