PHP: Cookie domain / subdomain control

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

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

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

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

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

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

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

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


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

setcookie('cookiename','cookievalue',time()+(3600*24),'/');

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


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

https://www.rfc-editor.org/rfc/rfc6265#section-5.4

Tags:

Php

Cookies