Search code examples
phpsetcookie

PHP setcookie for the entire domain name


I use this function to set a cookie for the entire domain name:

setcookie("tuittingID", $random, mktime(0, 0, 0, 12, 31, 2015), '/', '.domainname.com');

The problem now is that I do not know what domainname.com will be, since this script will be used by different people on different domain names.

I have top find a way to do the same thing but without having the client editing that line.

Is there a way?

Let me know please.


Solution

  • Check the $_SERVER superglobal. It contains various parts of the address (for instance in $_SERVER['HTTP_HOST']), although you may still need to do some cutting yourself. You can explode the hostname into an array, using the .. as a separator. Combining the last two items, you get the domain name (SLD + TLD).

    If this code is to be used as a library, I would offer the user (of the library) the possibility to use the full domain, only the second level domain, or a custom setting.