Search code examples
phpcookiessetcookie

PHP cookie writes on incorrect domain


I have a cookie that I use on my app. It looks like this:

+-------+-------+-----------------------+-------+----------+
| Name  | Value | Domain                | Path  | Expires  |
+-------+-------+-----------------------+-------+----------+
| foo   | bar   | my.domain.tld         | /     | Session  |
+-------+-------+-----------------------+-------+----------+

In a section of my script, based on some condition, I'm trying to change the value of a cookie. I'm using this code:

// overwrite cookie
if($condition){
  setcookie("foo", "cat", 0, "/", "my.domain.tld");
}

Afterward, my cookie data looks like this:

+-------+-------+-----------------------+-------+----------+
| Name  | Value | Domain                | Path  | Expires  |
+-------+-------+-----------------------+-------+----------+
| foo   | bar   | my.domain.tld         | /     | Session  |
| foo   | cat   | .my.domain.tld        | /     | Session  |
+-------+-------+-----------------------+-------+----------+

How come a . is be prepended to the domain? I want to overwrite the existing cookie.


Solution

  • As it turns out, specifying no domain seems to work:

    setcookie("foo", "cat", 0, "/");
    

    Expected cookie data:

    +-------+-------+-----------------------+-------+----------+
    | Name  | Value | Domain                | Path  | Expires  |
    +-------+-------+-----------------------+-------+----------+
    | foo   | cat   | my.domain.tld         | /     | Session  |
    +-------+-------+-----------------------+-------+----------+
    

    Strange, but it works.