Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Sharing $ SESSION variables between www and non-www URLs

4:36 pm on Feb 11, 2008 (gmt 0)

Junior Member

10+ Year Member

joined:July 28, 2006
posts: 168
votes: 0

Hi, I have the issue that when I am on my site...

www.example.com and I have session variables, if i ever switch to the non-www versiont (example.com) I lose my session variables.

Is there a way to have both the www. and the non www. versions share the same $_SESSION variables?


5:14 pm on Feb 11, 2008 (gmt 0)


WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
votes: 2

Yes. Have a closer look at the cookie specification. There is a link to it on the setcookie [php.net] function page. Actually, it is the
argument on the PHP manual page there that describes how you can overcome your issue.
5:19 pm on Feb 11, 2008 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member whoisgregg is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Dec 9, 2003
posts: 3416
votes: 0

I'd highly recommend approaching this problem from a different direction... Standardize your site on one version or the other and redirect people to the correct version. Not just for session control, but also to keep from splitting your inbound link juice across multiple domains and to minimize duplicate content.

Add code similar to the following to the top of each page (or hopefully you have a global include file you can add this to):

if($_SERVER['SERVER_NAME'] != 'www.example.com'){
header('Location: http'.((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'On')? 's' : '').'://www.example.com'. $_SERVER['REQUEST_URI'], true, 301);

I say similar because I just wrote that off the top of my head, so it's completely untested and probably totally wrong. ;)