sarkolata
sarkolata

Reputation: 360

PHP $_SESSION value differs on www

I have a website. People can login it on here

sub.domain.com

If they login here, the session will do its job and user will be logged in. On any page at sub.domain.com, the session value be will returned so it will work fine.

But site can also be reached from www.sub.domain.com . When user logins at sub.domain.com, the session value is empty at www.sub.domain.com. I mean if user logs in at sub.domain.com, When he navigates to www.sub.domain.com, site will say 'please login', but user was already logged in at site without 'www'. Hope it was all clear, thank you.

Upvotes: 0

Views: 261

Answers (4)

Aurimas Ličkus
Aurimas Ličkus

Reputation: 10074

Add in your main script at the top, before session_start.

 ini_set('session.cookie_domain', '.domain.com' );

If you running PHP with suhosin enabled, try disabling there settings too

  ini_set("suhosin.session.cryptdocroot", "Off");
  ini_set("suhosin.cookie.cryptdocroot", "Off");

Source PHP bug tracker

Thanks to @RandomDave

You could dynamically determine the domain from $_SERVER['HTTP_HOST'] so you don't have to hard-code the domain name

  ini_set('session.cookie_domain', strtolower(substr($_SERVER['HTTP_HOST'], 0, 4)) == 'www.' ? substr($_SERVER['HTTP_HOST'], 3) : '.'.$_SERVER['HTTP_HOST'] );

Upvotes: 3

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

You can also add a .htaccess at the root of your site like

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^sub\.domain\.com
RewriteRule ^(.*)$ http://www.sub.domain.com$1 [R=permanent,L]

Upvotes: 0

Rudi Visser
Rudi Visser

Reputation: 21989

PHP Sessions use cookies to store the session identifier, if you're browsing over www. that is where the cookie will be set.

You can alleviate this issue by setting the session cookie domain prefixed with a dot, which will act essentially as a wildcard for *.domain.com by using .domain.com. You do this with session_set_cookie_params like so:

session_set_cookie_params(0, '/', '.domain.com');

A safer example would use session_get_cookie_params and re-pass the other values back in. Even better, you could modify the php.ini on your server to set session.cookie_domain value to be .domain.com (you could also use ini_set for this).

Upvotes: 0

xdazz
xdazz

Reputation: 160883

Set the cookie_domain for your session.

ini_set('session.cookie_domain', '.domain.com' );

Or change this setting in your php.ini.

Upvotes: 0

Related Questions