[ACCEPTED]-PHP: Cookie domain / subdomain control-cookies

Accepted answer
Score: 24

PHP's cookie functions automatically prefix 3 the $domain with a dot. If you don't want 2 this behavior you could use the header function. For 1 example:

header("Set-Cookie: cookiename=cookievalue; expires=Tue, 06-Jan-2009 23:39:49 GMT; path=/; domain=subdomain.example.net");
Score: 22

If you run your PHP script under "http://subdomain.example.net", don't use the domain parameter:


You 2 will get a cookie with "subdomain.example.net" (and 1 not ".subdomain.example.net")

Score: 14

If you read all of RFC 6265, you'll realize 2 that the only proper way to have a "host-only" cookie 1 is to NOT set the domain attribute.


Score: 11

I realise this is an old question but I 12 was having this problem and none of the 11 answers above quite did it.

I wanted to set 10 the session cookie for a subdomain, but 9 also enable httponly and secure.

To avoid 8 a leading . infront of the subdomain, Kevin 7 and stolsvik are correct don't set the domain 6 attribute.

So to do this and still be able 5 to set httponly and secure mode, set the 4 domain to NULL as follows:

session_set_cookie_params(0, '/', NULL, TRUE, TRUE);

You will now have 3 a session cookie, for a specific subdomain 2 (without a leading .) with httponly and 1 secure set to true.

Score: 2

This may help someone (i spent some hours 5 to figure this out). After make the changes 4 in the source files and before you test 3 it, close your browser to properly destroy 2 PHPSESSIONID in all domains and subdomains.

Hope 1 this save some time!

Score: 0

I was having a problem to set cookies on 3 wordpress and this helped me, the domain 2 value was the key to get it working in all 1 the pages

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;

setcookie("cookie_name", 'cookie_value', 0, '/', $domain);

More Related questions