0

Possible Duplicate:
Allowed characters in cookies

I need to separate values in a cookie. So I chose &'s to separate name=value pairs just like I would in a URL. There can be multiple values too for a name, so I separate those with a colon.

My question is if this is legal? Do I need to URL encode everything? The values can have colons inside them, so I thought I'd URL encode the values in order to make sure the colons in a value don't conflict with the separator character. I read somewhere that enclosing the entire cookie with apostrophes works too, does that make sense?

If this is not legal, what's the best way to store my multiple name/value pairs that often have multiple values per name (in a specific order, so I can't just duplicate the name/values)?

Community
  • 1
  • 1
at.
  • 50,922
  • 104
  • 292
  • 461
  • Is there a reason you’re not using one cookie per name/value pair? – Josh Lee Nov 27 '10 at 04:09
  • I guess 2 reasons, but neither are very important... so I'm certainly open to changing that and doing away with the &s. First, there might be many name/value pairs and I don't want to inundate someone monitoring their cookies and risk problems there. Secondly, it just makes for easier processing in JavaScript... all I have to do is $.each(cookie.split('&'), ... – at. Nov 27 '10 at 04:13
  • Duplicate of [Allowed characters in cookies](http://stackoverflow.com/questions/1969232/allowed-characters-in-cookies). I couldn't answer better than Bobince already did. By the way, I'd investigate if utilizing the server side session isn't a better approach since cookies are pretty limited in the amount of information they can hold. – BalusC Nov 27 '10 at 04:22
  • You could encrypt the data before storing it in the cookie, then, you save any values you want. – James Black Nov 27 '10 at 04:26
  • @BalusC - Bobince did in fact give a great response, thanks. @James Black - what is the best way to encrypt data in a cookie? Base64? simple URL Encode? – at. Nov 27 '10 at 17:10

1 Answers1

0

You will have to percent-escape the characters contained in the name and value parts of the cookie, just like you should already be doing. For example, = would become %3D, & would become %26, etc. Just build up the string you want to use for your cookie value and run it through your language/framework's URI escaping function. If your framework has a method for setting cookies and it takes distinct name/value arguments, it should be doing this for you.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • My framework is Spring 3/JEE 6 and they do not, according to the JavaDoc I'm reading, escape or unescape cookies at all. – at. Nov 27 '10 at 17:11
  • Then you will have to do what I've suggested and use a URI escaping function on the name and value prior to sending it to the browser. – cdhowie Nov 27 '10 at 17:26