35

How can I set a cookie in PHP that is readable both in HTTP and HTTPS?

If this isn't possible, what can be done? Set two cookies?

Paulo Coghi
  • 13,724
  • 14
  • 68
  • 90
  • What browser are you using? I am noticing that in IE9 that I have a cookie in HTTPS and HTTP with the same key but each has a different value. Even when the cookie is not a secure cookie. – Tony Topper Jan 25 '12 at 20:13
  • When I asked that question, I looked for solutions that work on major browsers. And yes, the solution presented worked. – Paulo Coghi Jan 27 '12 at 13:16
  • Just use the same domain (or a proper parent domain) and cookies will be accessible via both HTTP and HTTPS by default. If you want to be explicit, set `$cookie->setHttpOnly(false)` with https://github.com/delight-im/PHP-Cookie – caw Jul 12 '16 at 23:56

2 Answers2

73

By default, a cookie can be read by both http and https at the same URL.

However, a server can optionally specify the 'secure' flag while setting a cookie this tells the browser to only send it over a secure channel, such as an SSL connection.

In this case the cookie will only be sent over https. A cookie not marked as secure will be sent over both http and https.

Andrew Strong
  • 4,303
  • 2
  • 24
  • 26
  • Is a cookie not marked as secure, secure when sent over https? (I imagine the answer is yes). – Oversteer Aug 09 '12 at 11:23
  • @Oversteer yes, it is secure over https. The problem is that if a mixture of http and https is used, the cookie is only secure part of the time. – Andrew Strong Aug 15 '12 at 23:21
27

Assuming your domain name remains the same except for the resource type, cookies in PHP (or any language) can be read from both HTTP and HTTPS.

e.g.:

http://www.example.com
https://www.example.com

In this example, the cookies will be readable from each other.

Michael Easter
  • 23,733
  • 7
  • 76
  • 107
David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
  • you forgot to put the example – Paulo Coghi Feb 23 '10 at 20:18
  • 4
    The example is right there. I'm demonstrating that the same URL with just the resource identifier changed will still use the same cookies. Cookie domains are based on DNS name, and do not have awareness of protocol. To clarify, you do not need to do anything special at all to receive your desired effect. See the Cookie spec for more information: http://curl.haxx.se/rfc/cookie_spec.html – David Pfeffer Feb 23 '10 at 20:37