View Full Version : Need to get cookie domain

08-10-2007, 12:43 PM

I set my cookies using setcookie like this for exp:

setcookie("username", $_SESSION['username'], 2147483647, "/", ".$cookiedomain", 0);

where $cookiedomain is my domain name without www, like mydomain.com, mysite.net etc.

My question is, can I get this variable automatically from an environment or server variable? $_SERVER["HTTP_HOST"] gives something like www.mydomain.com and I could trim it but will it give correct value on every server? And, which one is more reliable, ENV or SERVER?


08-10-2007, 12:52 PM
try this, this has worked for me plenty of times

$cookiedomain = $_SERVER["SERVER_NAME"];

setcookie("username", $_SESSION['username'], 2147483647, "/", ".$cookiedomain", 0);

good luck

08-10-2007, 01:18 PM
Hi, thanks for the reply!

You determine the $cookiedomain as the value of $_SERVER['SERVER_NAME']. I guess this may work for you cause you always used the same server or a shared hosting? Maybe the SERVER_NAME can be different something than a domain name.

And, your cookie will be useful only on www domain. I want it to be useful for people without www domain too.

So, I wrote the following:

$cookiedomain = $_SERVER['HTTP_HOST'];
if(strtolower(substr($cookiedomain, 0, 4)) == 'www.') {
$cookiedomain = substr($cookiedomain, 4);
$cookiedomain = '.' . $cookiedomain;

setcookie("username", $_SESSION['username'], 2147483647, "/", $cookiedomain, 0);

08-10-2007, 01:47 PM
it shouldn't do that, it takes the server name from the url so if they go http://mysite.com/ it will output mysite.com if it is http://www.mysite.com the output will be www.mysite.com