Using PHP sessions across subdomains
By default, PHP uses the 'PHPSESSID' cookie to propagate session data across multiple pages, and by default it uses the current top-level domain and subdomain in the cookie declaration.
Example: www.domain.com
The downside to this is that the session data can't travel with you to other subdomains. So if you started a session on www.domain.com, the session data would become unavailable on forums.domain.com. The solution is to change the domain PHP uses when it sets the 'PHPSESSID' cookie.
Assuming you have an init file that you include at the top of every PHP page, you can use the ini_set() function. Just add this to the top of your init page:
ini_set('session.cookie_domain',
substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));
This line of code takes the domain and lops off the subdomain.
Example: forums.domain.com -> .domain.com
Now, every time PHP sets the 'PHPSESSID' cookie, the cookie will be available to all subdomains!
Example: www.domain.com
The downside to this is that the session data can't travel with you to other subdomains. So if you started a session on www.domain.com, the session data would become unavailable on forums.domain.com. The solution is to change the domain PHP uses when it sets the 'PHPSESSID' cookie.
Assuming you have an init file that you include at the top of every PHP page, you can use the ini_set() function. Just add this to the top of your init page:
ini_set('session.cookie_domain',
substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));
This line of code takes the domain and lops off the subdomain.
Example: forums.domain.com -> .domain.com
Now, every time PHP sets the 'PHPSESSID' cookie, the cookie will be available to all subdomains!

Well, yes, the browser will send the session cookie to both servers. But, the session info is only stored on one server. The only way to overcome this would be to store session data in a database that both servers can access.
I have added
ini_set('session.cookie_domain', '.my-domain.com');
session_start();
at the beginning of my config file which is included in every page but If I login on one sub-domain, I can not access session data on other sub-domains or www.
Am I missing something ???
This will NOT work:
ini_set('session.cookie_domain', '.localhost');
sub1.localhost and sub2.localhost will not share the same session but...
This will work:
ini_set('session.cookie_domain', 'example.localhost');
Now sub1.example.localhost and sub2.example.localhost will both work with the same session.
Hope that makes sense.