-1

Possible Duplicate:
PHP: Cookie domain / subdomain control

I have tow page a.php and b.php. I am running my a.php page with the url as http://www.domain.com/a.php. Here, page contains some session values.

Ex: $_SESSION['name']='my name';

In b.php i am printing above session value. If i access my b.php page with the url http://www.domain.com/b.php, Session values are working fine.

Ex: echo $_SESSION['name']; //Output 'my name';

If i access the same page with the url http://domain.com/b.php , session values are not working.

EX: echo $_SESSION['name']; //No Result

what is the problem and how can i solve this.

Community
  • 1
  • 1
Hearaman
  • 8,466
  • 13
  • 41
  • 58
  • 5
    That is the default behaviour of cookies. It can be changed, but why do you serve `domain.com` and `www.domain.com` in the first place? That often leads to duplicate content which is not good for search engines. Why not redirect from one to the other so URLs are consistent? – Pekka Mar 02 '12 at 09:51

3 Answers3

2

You can enable your session on all subdomains with session_set_cookie_params() function

session_set_cookie_params ( 0, '/'  '.domain.com');
Vytautas
  • 3,509
  • 1
  • 27
  • 43
1

There are a lot of similar questions to this, did you search before posting ;)?

In summary:

  • Sessions work with cookies
  • www is not a special string, that's just the www subdomain of example.com
  • A cookie can only be accessed by the domain and direct subdomains for where it is set
    • A cookie set on example.com (or rather, "."example.com) applies to any subdomain
    • A cookie set on www.example.com cannot be accessed from example.com

All that being said - you can ignore even thinking about it if you simply redirect from www.example.com -> example.com - or vice versa of course.

AD7six
  • 63,116
  • 12
  • 91
  • 123
1

It's best that you set a redirect from www.example.com to example.com or vice versa to avoid duplicate content. However, you can modify your php.ini to choose the domain you want. If your host lets you edit your php.ini, add this to it:

session.cookie_domain = example.com

If it doesn't, create a file called .htaccess at the root of your website (usually public_html or htdocs) and add:

php_value session.cookie_domain example.com

Obviously you will need to replace example.com with the domain of your website without www or any other subdomains.

kirb
  • 2,033
  • 1
  • 18
  • 28