I am using CI.
I want to share session over subdomains
And I'm using database to store sessions
I've tried this
ini_set('session.cookie_domain', substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));
if(session_id ==''){session_start();}
That means x.y.com and z.y.com will use common session
help me, pls
Considering the fact that you already know your domain name, is there a reason why you use substr to determine it? You could would be much more readable if you just used:
ini_set('session.cookie_domain', '.domain.tld');
For cookies to work across multiple subdomains, the cookie domain must start with a dot (.) followed by the common part of all the sub-domains (most likely domain.tld.)
Also, the second line of your post, the one where you check if the session needs to be started is wrong. You're missing a set of parentheses after session_id because it's a function and not a constant. The conditional statement (if) would always fail causing session_start() to be called every time.
if ( empty(session_id()) ) session_start();
Set a new session.name before changing other session settings and starting a new session.
See Notes Below:
//Name your session for changes to be applied to.
session_name('my_session'); //Any arbitrary short name. Must have at least on letter char.
//Force a common cookie domain to apply to all subdomains.
ini_set('session.cookie_domain', '.domain.com'); //Change '.domain.com' accordingly.
//Start the Session if session_id() returns nothing.
if( empty( session_id() ) ) { session_start(); }
This has consistently worked for me. The php.net documentation on this is minimal, but, it appears to be the consensus with many in the community.
I am assuming that this above would go into the login file that processes the login and starts the session?
I have the code below in my log in file. Yes, I am a cut and paste coder :)
Does this mean it should work across subdomains since it says it's persistent sessions?
@session_start();
$usersession = generate_session(100);
$host_name = '.'.str_replace('www.','',$_SERVER['HTTP_HOST']);
if($_POST['persistent'] == 'yes'){
setcookie("usersession", $usersession, time()+ ($_POST['persistentFor']*7*24*60*60), "/", $host_name, 0);
}
$_SESSION['usersession'] = $usersession;
$user_ip = get_ip();
$insert_session = @mysql_query("INSERT INTO `memb_usersessions`
(`session_id`,`user_id`,`session_date`) VALUES ('$usersession','$get_user[user_id]',NOW())");