Naming cookies - best practices

PhpCookiesNaming Conventions

Php Problem Overview


What should cookie names look like?

Should they be:

  • lower_case
  • CamelCase
  • Underscore_Camel_Case
  • UPPER_CASE

Or should they be something else?

Php Solutions


Solution 1 - Php

appname_meaningfulname

Solution 2 - Php

Keep in mind that this cookie is sent with every request, so imho, just use the smallest name you can, and document your code nicely.

Solution 3 - Php

It should be something that avoids naming conflicts with arbitrary _GET and _POST params you might be using, since _REQUEST wraps all three global arrays (!), with precedence depending on how your variables_order setting is set in php.ini. In other words, if you have a _COOKIE named "x" and a querystring param named "x", and you ask for $_REQUEST["x"], you get the cookie value when you might want/expect the GET param. This is especially problematic if your cookies are scoped to your website root "/", and not to the folder where they are consumed.

So I say, two best practices:

  1. make sure you limit scope of your cookies to the path where they are read and written, (third argument of setcookie() method does this)
  2. give your cookies some sort of cookie-specific naming convention. I suggest reverse website, like java namespaces, then ".".{appname}.".".{friendly cookie name camel cased} So, if your site is www.testsite.com, and your app is foo, and your variable is "bar bar bar bar bar barann", it would be "com.testsite.foo.barBarBarBarBarBarann"

Solution 4 - Php

I use whatever style the coding standards for the project call for.

Generally I prefer camelCase for naming schemes, but whichever one pays the bills is the one I'll go with.

Solution 5 - Php

Maybe you won't like my answer:

Don't use your own cookies but store data in server sessions. So you only need one cookie (to reference the session id) and how you name that plays no role.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEmanuil RusevView Question on Stackoverflow
Solution 1 - PhpIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PhpMatthieuPView Answer on Stackoverflow
Solution 3 - PhpWillieMackView Answer on Stackoverflow
Solution 4 - PhpzombatView Answer on Stackoverflow
Solution 5 - PhpNineBerryView Answer on Stackoverflow