1234ru
1234ru

Reputation: 842

Can't make cookies work for subdomain

Update: looks like it didn't work because of local machine hosting, particularly short domain names used (like '.t'). The same code on remote server with actual (real-life) domain names usage works fine.

There are two domains (the root and it's sub one) both running looking at the same webserver's directory, thus, working on the exact same scripts. (I have Apache/PHP run on Windows XP on a home computer, so I choose to use short names for the local hosts - 't' and 'a.t' respectively).

session_set_cookie_params(
          24*3600, // 24 hours 
          '/',     // all paths
          '.t',    // 't' and all sub-domains
          FALSE,   // not secure
          FALSE    // not http-only
     ); 

session_start();

if ($_SERVER['HTTP_HOST'] == 't') 
    setcookie(
            'test',           // cookie name
            'yes',            // cookie value
            time() + 24*3600, // expires after 24 hours
            '/',              // all paths
            '.t',             // t and all subdomains
            FALSE,            // not secure
            FALSE             // not http-only
        );

echo $_SERVER['HTTP_HOST'] . '<br>';

print_r($_COOKIE);

Here what I have for the root local host:

t 
Array ( [PHPSESSID] => 23lhahncni8ekeqj3j02u7qlq5 [test] => yes )

and for the subdomain:

a.t 
Array ( )

As you can see, the $_COOKIE array for the subdomain is empty, although corresponding cookies can be seen by the browser (Firebug, to be exact - I can see those two cookies in the tab where subdomain's page is opened). I can't figure out why is that happening.

I need to access $_COOKIE[test] for both domains. How can I accomplish that?

Upvotes: 0

Views: 786

Answers (1)

Barmar
Barmar

Reputation: 780798

You need to specify the domain in the call to setcookie():

setcookie('test', 'yes', 0, '/', '.t');

session_set_cookie_params() only sets the options for the cookie used to save $_SESSION, not cookies set using setcookie.

Upvotes: 1

Related Questions