2

I wonder how this quote from the PHP manual should be interpreted:

session.cookie_domain specifies the domain to set in the session cookie. Default is none at all meaning the host name of the server which generated the cookie according to cookies specification.

Does it mean that when calling session_start on URL www.somedomain.com/somepage.php the cookie will have the following form:

Set-Cookie  PHPSESSID=e48gh5mqggccgmn8172f0j5a06; path=/; domain=.somedomain.com

Or

Set-Cookie  PHPSESSID=e48gh5mqggccgmn8172f0j5a06; path=/; domain=www.somedomain.com

I have seen on index pages the first cookie header and on other pages a header without a domain.

Can someone bring some insight on this?

Thanks

Martin Dimitrov
  • 4,796
  • 5
  • 46
  • 62
  • [Some nice answers here](http://stackoverflow.com/questions/644920/allow-php-sessions-to-carry-over-to-subdomains). – Alex Sep 21 '11 at 10:00

3 Answers3

4

No, php will usualy set the cookie for the current domain ex: wwww.domain.com. To have everything consistent, you must either redirect all request to the same domain, or explicitly set the cookie for all subdomains.

EDIT: actualy, this is true for Firefox. I think PHP will not actualy set the domain, so the browser is free to use whatever he wants. Internet Explorer i think will set it for any subdomain

Dan Bizdadea
  • 1,292
  • 8
  • 15
  • Thanks. PHP actually wouldn't bother to set the domain so the cookie it wil send is: `Set-Cookie PHPSESSID=e48gh5mqggccgmn8172f0j5a06; path=/` which is left for the browser to interpret. Further investigation is needed to figure which browsers do what but I guess it is not that important. – Martin Dimitrov Sep 21 '11 at 10:54
2

No PHP by default never set session cookie for all subdomains.

If you want to set a cookie across all subdomains then you can do this by using this code:

<?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);
?>

For reference please visit http://www.php.net/manual/en/function.session-set-cookie-params.php

Grant Palin
  • 4,546
  • 3
  • 36
  • 55
Peeyush
  • 4,728
  • 16
  • 64
  • 92
1

It does set the cookie for the domain visible in the client's browser (so, option 2 in your question). If you want to set a cookie for all subdomains you should call session_set_cookie_params() and put ".domain.com" in the $domain parameter.

Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57