0

did anyone know how to keep a session across subdomains?

i can access a specific cookie using two different subdomains, but a problem remains ... when i try to send a $_SESSION['test'] for a subdomain to another , it doesn't show up in the other :

subdomain1.domain.com/trial.php

<?php
ini_set("session.cookie_domain", ".domain.com");  // allow access to this cookie from any subdomain
session_start();      // create cookie
$_SESSION['test'] = "TEST1";  // lets try to send "TEST1" in the other subdomain
?>

subdomain2.domain.com/trial.php

<?php
ini_set("session.cookie_domain", ".domain.com");  
session_start();       // cookie already set
print_r($_SESSION);    // $_SESSION array is empty
?>

thanks, milkael

1 Answers1

3

Better store sessions in the database, and pass it around as cookies. PHP has a parameter (domain) in it's setcookie() to make a cookie available to the whole domain (including subdomains).

so, provided that your domain and subdomains access the same database (or at least has access to the database that holds sessions):

  • store session ids in the database (session ids should be unique for every user)
  • store the same session id in a cookie in the browser (available across domains)
  • when a user visits another subdomain of yours, just compare the cookie value with the value from the database and you'll know who that person is one and the same.
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • well, thanks for your reply , but i don't like making sessions by myself , i prefer to let PHP handle that. can you please debug the previous php code, so that the second subdomain extract the value of $_SESSION['test'] ? thanks – milkael sensei Feb 19 '12 at 13:29
  • *"The downside to this is that the session data can't travel with you to other subdomains."* - http://www.epigroove.com/posts/87/using_php_sessions_across_subdomains – Joseph Feb 19 '12 at 20:43
  • http://stackoverflow.com/questions/6318492/sharing-session-over-subdomains-in-php – Joseph Feb 19 '12 at 20:47