PHP Multi-Domain Sessions; ini_set Not Working?

SumWon picture SumWon · Jan 8, 2011 · Viewed 10.9k times · Source

I'm trying to set it up so if you log in to my website the session carries over to all sub-domains of my website. For example, if you go to domain.com and log in, then go to sub.domain.com, you'll already be logged in at sub.domain.com.

To my understanding, you would want to use ini_set('session.cookie_domain','.domain.com') and then session_start(), then set your session variables, but this isn't working.

Example of what I'm doing:

Code for domain.com:

<?php
 ini_set('session.cookie_domain','.domain.com');
 session_start();
 $_SESSION['variable'] = 1;
?>

Code for sub.domain.com:

<?php
 session_start();
 echo $_SESSION['variable'];
?>

But $_SESSION['variable'] isn't set.

I've also tried using ini_set() in the sub.domain.com code, but it made no difference. I've verified that setting session.cookie_domain is working by using ini_get().

What am I doing wrong? Thanks!

Answer

CarpeNoctumDC picture CarpeNoctumDC · Jan 8, 2011

First verify the ini_set

<?php
ini_set('session.cookie_domain','.domain.com');

echo ini_get('session.cookie_domain');

session_start();  
$_SESSION['variable'] = 1; 

?> 

Update:

Just thought about it.. Did you also try:

<?php

session_set_cookie_params( 0, "/", ".domain.com", false, false); 
session_start();  
$_SESSION['variable'] = 1; 

?> 

Update 2: ALternate handling (manual cookie handling)

<?php

session_start();  
session_regenerate_id();
$_SESSION['variable'] = "String Test";

setcookie('PHPSESSID',session_id(),time()+86400,'/','.domain.com');
echo session_id();
?> 

and in the subdomain file

<?php  
if (isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) session_id($_COOKIE['PHPSESSID']);

session_start();  
echo $_SESSION['variable'] . "<br />"; 
echo $_COOKIE['PHPSESSID'] . "<br />";
echo session_id();
?> 

Three lines you could add to every file to hand off / handle session info

if (isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) session_id($_COOKIE['PHPSESSID']);
session_start();  
if (!isset($_COOKIE['PHPSESSID'])) setcookie('PHPSESSID',session_id(),time()+86400,'/','.domain.com');

What info are you passing through the session? Or are you using it to handle logins, etc?