maček
maček

Reputation: 77816

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.

Upvotes: 6

Views: 280

Answers (3)

maček
maček

Reputation: 77816

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.

Upvotes: 0

Zak
Zak

Reputation: 25237

From the documentation:

The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you'd set it to '.example.com'. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the » spec for details.

And the tail matching spec is here:

http://curl.haxx.se/rfc/cookie_spec.html

Upvotes: 0

Mark Grey
Mark Grey

Reputation: 10257

http://www.php.net/manual/en/function.setcookie.php#93641

The answer is discussed in a post on the php manual.

Cookie data is set by the browsing agent, and so is handled differently depending on the process the browser uses.

Upvotes: 1

Related Questions