1

My site uses PHP sessions to keep track of a logged in user. Every page has session_start(); implemented properly, however in chrome when I place www. in from of the domain name it does not use the session variables. When I replace it back without the www. it works fine again, so the variables are not unset but rather just not being used.

In Firefox strangely it is the other way around. www. works and without does not. Is there a way around this? I'm having trouble because I'm using PayPal to redirect to my site and I can't have my users have to log out and back in directly after.

Arun
  • 626
  • 10
  • 29
  • 3
    `www` is diferent with `without www` in terms of session cookie speaking. You should choose one. This is why sites such as SO forces their visitors to remove the www. And also, it's not a good practice to have two exactly-the-same websites on different (sub) domains. – rlatief Feb 01 '13 at 17:59
  • It sounds like the session cookie is set to run under a specific domain. I don't actually know how that's done, but you could check the session cookie settings. Either that or just redirect from `www` (or back) every time – Explosion Pills Feb 01 '13 at 18:01

2 Answers2

8

www.example.com and example.com are NOT the same website. They usually are, but only by convention. www.example.com is a subdomain of example.com

For this reason, cookies set on example.com will NOT be used on www.example.com and vice versa, because it would be unsafe to assume they are the same thing.

You can override this behaviour to some extent by allowing the session cookie to work on all subdomains as well as the main domain by setting the php.ini setting session.cookie_domain to .example.com (replace with your own domain name, of course)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Can be done on a per-script basis by calling [`session_set_cookie_params($lifetime, $path, $domain)`](http://www.php.net/manual/en/function.session-set-cookie-params.php) before `session_start()`. Defaults would be: `session_set_cookie_params(0, '/', '.mydomain.com');` – Sammitch Feb 01 '13 at 18:09
3

You should either set the cookie_domain in PHP or make sure your users only see your site with www or without www. You can use .htaccess (apache server) to accomplish this.

Example to set your cookie domain for multiple subdomains:

session_set_cookie_params(0, '/', '.example.com'); 
session_start(); 
Green Black
  • 5,037
  • 1
  • 17
  • 29