By dragonmantank


2009-06-30 15:12:17 8 Comments

I am trying to set up the following:

auth.domain.com
sub1.domain.com
sub2.domain.com

where if the user visits sub1.domain.com or sub2.domain.com and they are not logged in, they get pushed over to auth.domain.com and can log in. sub1.domain.com and sub2.domain.com are two separate applications but use the same credentials.

I tried setting the following in my php.ini:

session.cookie_domain = ".domain.com"

but it doesn't seem to be passing the information from one domain to the other.

[Edit]

I tried the following:

sub1.domain.com/test.php

session_set_cookie_params(0, '/', '.domain.com');
session_start();
print session_id() . "<br>";
$_SESSION['Regsitered'] = 1;
echo '<a href="http://auth.domain.com/test.php">Change Sites</a>'

auth.domain.com/test.php

session_set_cookie_params(0, '/', '.domain.com');
session_start();
print session_id() . "<br>";
$_SESSION['Checked'] = 1;
print_r($_SESSION);

The session IDs are exactly the same but when I dump out the $_SESSION variable it doesn't show both keys, just whatever key I set under each domain.

[Edit 2]

I updated [Edit]

16 comments

@user3232196 2016-11-03 17:13:52

I can't speak for other versions of PHP, but in 5.6.6, simply setting the session.cookie_domain value in the php.ini file did the trick to allow all of my subdomains on iPage to share the same set of session variables.

Be sure to remove any existing cookies related to your domain from your browser to test.

session.cookie_domain = '.yourdomainname.org'

Oh, don't know if it makes any difference but I'm also using session autostart.

session.auto_start = 1

@Willian Santana 2016-07-26 19:06:54

I had a similar problem, however, this solution was good for me, perhaps will help others in the future

edit the php.ini

session.cookie_domain = ".example.com"

the magic is here

suhosin.session.cryptdocroot = Off

suhosin.cookie.cryptdocroot = Off

https://www.sitepoint.com/community/t/sessions-across-subdomains-domain-com-phpsessid-changes/3013/19

@Terry Lin 2015-05-12 17:56:34

I have confirmed. joreon's answer is correct. I cannot comment because my reputation is not enough so I post my comment here.

Define the constant in a config file. If you want to change it, no need to modify whole files.

define('ROOT_DOMAIN',   'mysite.com');
define('PHP_SESSION_NAME', 'MYSITE'); 

The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time.

Use the following code to start using session

session_name(PHP_SESSION_NAME);
session_set_cookie_params(0, '/', '.' . ROOT_DOMAIN);
session_start();

I'm using this function:

function load_session() {
    if (session_status() == PHP_SESSION_NONE) {
        session_name(PHP_SESSION_NAME);
        session_set_cookie_params(0, '/', '.' . ROOT_DOMAIN);
        session_start();
    }
    else {
        if (session_name() != PHP_SESSION_NAME) {
            session_destroy();
            session_name(PHP_SESSION_NAME);
            session_set_cookie_params(0, '/', '.' . ROOT_DOMAIN);
            session_start();
        }
    }
}
load_session(); // put it in anywhere you want to use session

@Limitless isa 2014-08-28 16:26:39

Sub domain and root domain Cookie Sessions Combined Use

Resource: http://php.net//manual/tr/function.session-set-cookie-params.php

I've tested works

sub.exampledomain.com/sessionadd.php?id=123

exampledomain.com/sessionview.php // 123

-- Codes

<?php 
$currentCookieParams = session_get_cookie_params(); 

$rootDomain = '.example.com'; 

session_set_cookie_params( 
    $currentCookieParams["lifetime"], 
    $currentCookieParams["path"], 
    $rootDomain, 
    $currentCookieParams["secure"], 
    $currentCookieParams["httponly"] 
); 

session_name('mysessionname'); 
session_start(); 

setcookie($cookieName, $cookieValue, time() + 3600, '/', $rootDomain); 
?>

@mohsin.mr 2014-07-09 10:50:18

Simply try using following code just above session_start() method

$sess_life_time = 21600; //in seconds
$sess_path = "/";
$sess_domain = ".you-site-name.com";
$sess_secure = true; // if you have secured session
$sess_httponly = true; // httponly flag

session_set_cookie_params($sess_life_time, $sess_path, $sess_domain, $sess_secure, $sess_httponly);

@Valentin Florea 2013-12-03 14:10:00

Had this exact problem - I wanted session values created on x.example.local to be available on example.local and vice-versa.

All solutions I found said to change the Session domain by using php_value session.cookie_domain .example.local in .htaccess (or via php.ini or via ini_set).

The catch was I was setting the session.cookie_domain for all subdomains (so far ok) but also for the main domain. Setting the session.cookie_domain on the main domain is apparently a no-no.

Basically the way it worked for me:

  • set the session.cookie_domain for ALL SUBDOMAINS.
  • don't set it for the main DOMAIN

Oh yes, please make sure the domain has a TLD (in my case .local). Http protocol doesn't allow cookies/sessions to be stored on a domain without .tld (ie localhost won't work, but stuff.localhost will).

EDIT: Also make sure you always clear your browser cookies while testing/debugging sessions across subdomains. If you don't, your browser will always send the old session cookie which probably doesn't have the correct cookie_domain set yet. The server will revive the old session and therefore you'll get false negative results. (in many posts it's mentioned to use session_name('stuff') for the exact same effect)

@Andrii Nemchenko 2013-11-17 07:03:45

Use it on every domain/subdomain:

session_name('name');
ini_set('session.cookie_domain', '.example.com');
ini_set('session.save_path', '/var/lib/php/session');
session_start();

Path for session.save_path can be different for your case but it should be the same on every domain/subdomain. It is not always true by default.

@Kamal Kumar 2016-07-04 10:34:33

works perfect for me thanks

@user953985 2012-12-21 03:55:28

I have read all answers above, I think my answer is helpful for people googling this.

* Make sure the browsers send session cookie back to servers (of domain and sub-domains), set session cookie domain as ".example.com".

* Make sure php find the right "target" to restore session var - If domain and subdomains point to the same machine (maybe different virtual hosts), make sure "session_save_path" is the same for all (I tested) - If domain and subdomains point to different machines, the common storage (like database) is best for saving and restoring session data (I didn't test yet). Use "session_set_save_handler" to do that.

@Ivan 2010-10-05 20:22:21

Use this , it works:

ini_set('session.cookie_domain', 
    substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));

@chacham15 2015-01-20 23:58:50

this looks like its setting the cookie for the tld...or am i missing something?

@xtds 2012-04-12 17:27:13

I solved it like this

ini_set('session.cookie_domain', '.testdomain.dev');
session_start();

Because I was working on localhost

ini_set('session.cookie_domain', '.localhost');

wasn't working, it sees .localhost as the toplevel instead of .com/.local/... (I suspect)

I also used .dev because working on OS X doesn't seem to resolve .com as first in HOSTS

@dennis 2015-02-01 10:41:10

Also fixed it for my machine - Ubuntu 14.04

@Ian 2012-01-17 16:46:08

I know this is old but this works fine for me with multiple domains and sub domains on the same box.

<?php
define('site_domain','domain.com');
session_set_save_handler('_open',
                         '_close',
                         '_read',
                         '_write',
                         '_destroy',
                         '_clean');

function _open(){

    global $_sess_db;

$db_user = 'user';
$db_pass = 'pass';
$db_host = 'localhost';

if ($_sess_db = mysql_connect($db_host, $db_user, $db_pass)){

    return mysql_select_db('database', $_sess_db);

}

return false;

}

function _close(){

    global $_sess_db;
    return mysql_close($_sess_db);

}

function _read($id){

    global $_sess_db;
    $id = mysql_real_escape_string($id);
    $domain = mysql_real_escape_string(site_domain);
    $agent = mysql_real_escape_string(isset($_SERVER['HTTP_USER_AGENT']));

    $sql = "SELECT data
    FROM sessions
    WHERE id = '$id' AND domain = '$domain' AND agent = '$agent'";

     if ($result = mysql_query($sql, $_sess_db)){

         if (mysql_num_rows($result)){
             $record = mysql_fetch_assoc($result);
             return $record['data'];
        }

    }

    return '';

}

function _write($id, $data){

    global $_sess_db;
    $access = time();

    $id = mysql_real_escape_string($id);
    $access = mysql_real_escape_string($access);
    $data = mysql_real_escape_string($data);
    $domain = mysql_real_escape_string(site_domain);
    $agent = mysql_real_escape_string(isset($_SERVER['HTTP_USER_AGENT']));

    $sql = "REPLACE INTO sessions
    VALUES ('$id', '$access', '$data', '$domain', '$agent')";

    return mysql_query($sql, $_sess_db);

}

function _destroy($id){

    global $_sess_db;
    $id = mysql_real_escape_string($id);
    $domain = mysql_real_escape_string(site_domain);
    $agent = mysql_real_escape_string(isset($_SERVER['HTTP_USER_AGENT']));

    $sql = "DELETE FROM sessions
    WHERE id = '$id' AND domain = '$domain' AND agent = '$agent'";

    return mysql_query($sql, $_sess_db);

}

function _clean($max){

    global $_sess_db;
    $old = time() - $max;
    $old = mysql_real_escape_string($old);
    $domain = mysql_real_escape_string(site_domain);
    $agent = mysql_real_escape_string(isset($_SERVER['HTTP_USER_AGENT']));

    $sql = "DELETE FROM sessions
    WHERE  access < '$old' AND domain = '$domain' AND agent = '$agent'";

    return mysql_query($sql, $_sess_db);

}

?>

@cale_b 2012-10-28 21:20:17

What question are you answering? And how does this improve/enhance on the 9 other answers?

@drewm 2011-06-25 12:49:12

One thing which can mysteriously prevent session data being read on a subdomain, despite cookies being correctly set to .domain.com is the PHP Suhosin patch. You can have everything configured correctly, as per the examples in the question, and it can just not work.

Turn the following Suhosin session settings off, and you're back in business:

suhosin.session.cryptua = Off 
suhosin.session.cryptdocroot = Off

@jeroen 2009-09-22 00:35:37

I don´t know if the problem still exists, but I just ran into the same problem and solved it setting a session name before calling session_set_cookie_params():

$some_name = session_name("some_name");
session_set_cookie_params(0, '/', '.some_domain.com');
session_start();

I have changed nothing in my php.ini but now everything is working fine.

@Roman 2011-02-10 17:04:40

I confirm, it solves the problem. I tired to get my answer there: stackoverflow.com/questions/4948340/…. But I found it here.

@Kit 2011-03-17 12:19:53

Works perfect! Been looking for ages for this. It was the $some_name = session_name("some_name"); that did it. Thank you and upvote.

@David Carroll 2011-07-03 07:28:35

Adding session_name("domain"); was the missing ingredient for me as well. The documentation on php.net regarding these session settings are lacking. There are community posts on php.net that indicate session.name needs to be defined before changes to session_set_cookie_params() can be applied.

@Daithí 2012-01-15 20:46:57

yep. confirmed. nice one was going around in circles for ages there ;)

@Daithí 2012-01-15 21:30:56

NOTE... had to close my browser and restart in order to get it to work on the life server. Leave out any ini_set("session.cookie_domain", ".domain.com"); cause this was causing it to create new session id with every refresh.

@Anupam 2013-05-05 16:47:43

worked like a charm, thanks :)

@Jānis Elmeris 2013-07-10 17:16:40

session_name() was not needed for me in a case where the cookie_domain was set to ".domain.com" from the beginning (of using the website). As I see it, what it does is getting around the problem that a user already has a PHPSESSID (standard session name) cookie stored for the subdomains, so even if I come from another subdomain with a new ".domain.com" cookie, my already stored "sub.domain.com" cookie is used instead. Setting a different session name discards those old cookies.

@Olav 2013-08-11 14:23:24

Please note that the domain needs to contain at least one dot. For example, session_set_cookie_params(0, '/', '.local'); does not work, whereas session_set_cookie_params(0, '/', '.domain.local'); does.

@imperium2335 2014-01-25 14:30:57

+1 Worked straight out of the box and solved my problem of having a user logged in and then changing the language (which uses subdomains i.e. fr.mysite.com, de.mysite.com).

@Abhishek 2014-05-29 04:50:35

@jeroen i also uploaded my website at a subdomain.. its domain is www.agicent.com,but my main files are at...ibuildmart.agicent.com/cms. Could please help me.Here sesion is not working.i am into this problem from many days.

@Homnath Bagale 2015-04-23 09:45:07

It worked for me too and solved the problem, feeling miracle.

@MDChaara 2016-01-17 13:21:10

This helped me sort out another problem. session array was cleared between pages so doing this actually made them variables stay where they're supposed to be. Thank you for the effort. A real life saver!

@Dr Magneto 2016-03-16 06:27:20

worked like a charm, thanks :)

@Buksy 2016-03-29 08:31:17

note: I had problem using "." character in session_name. There were no errors but session was empty each time, so try to change session name if it is not working :)

@sakabako 2009-06-30 18:58:54

A quick and dirty solution is to use this for your redirect:

header( $url.'?'.session_name().'='.session_id() );

this will add something along the lines of ?PHPSESSID=etnm7kbuf5lg0r6tv7je6ehtn4 to the URL, which tells PHP the session id it should use.

@dragonmantank 2009-06-30 19:08:48

It also leaves it highly vulnerable to session theft :) The problem isn't with the session IDs not matching (they are, see my updated post), but with the data not moving between the domains.

@Ian Jamieson 2013-02-18 10:02:45

Agreed, this is highly vulnerable leaving session ID in the query string.

@sakabako 2013-03-01 19:48:16

Cookies are also sent as plain text, this does not open any avenues that were not already open. I'm not saying it's a good solution, but it is no less secure than using cookies.

@Bastiaan ten Klooster 2017-10-09 09:33:58

It is less secure in the sense that users may be (tricked into) sharing their URL and thus share their active session ID. It is much less likely that a user will share their session ID cookie unwittingly.

@Thomas 2009-06-30 15:18:51

I get the idea that you don't want something like OpenID, like Joel is suggesting, but that you want to have access to the session data across multiple domains.

The only possibility that I can think of as a solution for that problem is to store the sessiondata in a database, and pull it out of that database.

@dragonmantank 2009-06-30 18:47:38

Right, while authentication is a part of what I want to do, I'm also interested in the session data that gets stored while the user is working.

@George Claghorn 2009-06-30 15:17:16

Try using:

session.cookie_domain = "domain.com"

Instead of:

session.cookie_domain = ".domain.com"

Note the missing period.

Be careful using this, though, because it is not supported by all browsers.

@gawpertron 2011-02-16 19:09:48

Which browsers are not supported?

@Kuf 2014-10-20 17:45:15

what browser support has to to here? this is a server side action.

Related Questions

Sponsored Content

26 Answered Questions

[SOLVED] Access-Control-Allow-Origin Multiple Origin Domains?

34 Answered Questions

[SOLVED] PHP: Delete an element from an array

  • 2008-12-15 20:28:55
  • Ben
  • 1964772 View
  • 1982 Score
  • 34 Answer
  • Tags:   php arrays

14 Answered Questions

[SOLVED] Why shouldn't I use mysql_* functions in PHP?

  • 2012-10-12 13:18:39
  • Madara Uchiha
  • 182167 View
  • 2202 Score
  • 14 Answer
  • Tags:   php mysql database

11 Answered Questions

[SOLVED] How do I expire a PHP session after 30 minutes?

  • 2009-02-06 13:14:14
  • Tom
  • 815458 View
  • 935 Score
  • 11 Answer
  • Tags:   php session cookies

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

28 Answered Questions

[SOLVED] How can I prevent SQL injection in PHP?

1 Answered Questions

[SOLVED] PHP Sessions across domains and shared multiple domains

3 Answered Questions

[SOLVED] PHP Multi-Domain Sessions; ini_set Not Working?

2 Answered Questions

[SOLVED] PHP Session fails on sub-domains

  • 2012-11-16 03:00:43
  • Gramps
  • 183 View
  • 0 Score
  • 2 Answer
  • Tags:   php html

Sponsored Content