8

Can HTTP cookie name contain dashes? Any reliable reference?

I've tried on Chrome and it's fine but I'm scared that other browsers may not allow because in PHP reference http://php.net/manual/en/function.session-name.php says:

name:
The session name references the name of the session, 
which is used in cookies and URLs (e.g. PHPSESSID). 
***It should contain only alphanumeric characters;*** 
jondinham
  • 8,271
  • 17
  • 80
  • 137
  • Look here http://stackoverflow.com/a/1969339/589909 or here http://www.uvsc.edu/disted/decourses/mct/2760/IN/krutscjo/lessons/10/dp_04.html – brenjt Sep 20 '13 at 02:11
  • possible duplicate of [Allowed characters in cookies](http://stackoverflow.com/questions/1969232/allowed-characters-in-cookies) –  Sep 20 '13 at 02:12
  • the only issue with the rules, is that every browser can do as it likes, we all know browsers see the same html differently. if your worried- then simply don't use them (-) –  Sep 20 '13 at 02:13

2 Answers2

16

A cookie name is defined as a 'token' within the parlance of the defining RFC6265. A token is defined in RFC2616 Section 2.2. Here's the extract:

   token          = 1*<any CHAR except CTLs or separators>
   separators     = "(" | ")" | "<" | ">" | "@"
                  | "," | ";" | ":" | "\" | <">
                  | "/" | "[" | "]" | "?" | "="
                  | "{" | "}" | SP | HT

As you see, a dash ("-") doesn't appear in the list, so it's OK.

  • 1
    +1 for pointing to a Standards document. I prefer linking directly to the IETF's html formatted RFC pages, though, where you can also link to concrete subsections: [RFC6265, 4.1.1 Syntax](http://tools.ietf.org/html/rfc6265#section-4.1.1). – Oliver Dec 12 '13 at 19:17
5

The spec says yes, my experience says no.

Using Chromium on Ubuntu, I developed a very odd problem with hyphens in cookies today which brought me to this question. Using a hyphen was causing the cookie to expire within microseconds (proven by dumping document.cookie to the console several times in the page load).

After tearing most of my hair out, I can clearly see now that

tibbed-WP_ID_313=true; expires=Wed, 03 Dec 2014 20:28:26 GMT

(two days away) lasts for about half way through the page load, whereas these variants

tibbedWP_ID_313=true; 
tibbed_WP_ID_313=true; 
tibbed:WP_ID_313=true;

all persist as they should.

This code has been working fine for the past couple of months. Go figure. I will be avoiding hyphens (dashes) from now on.

Justin Maxwell
  • 159
  • 2
  • 9
  • 2
    Currently having this issue, when using hyphens there are odd undocumented behaviours. By switching to camel case everything works as expected. Could not find information about this issue anywhere else – SocaBlood Mar 02 '22 at 19:10