Cookie basics

November 27, 2008 – 9:18 am

What is a Cookie?

Cookies, HTTP Cookies, Web Cookies or Tracking Cookies are small pieces of data stored by a website on client system. This data is sent back to the web server which initially set the cookie for any additional hit to the web server.

What are the uses of cookies ?

Cookies are majorly used for user authentication and carrying the active session across different page visits by a visitor in a visit session.

Say user A has a login at xyz.com. There is a login page where A enters his login details and goes ahead browsing pages in XYZ.com. Now cookies can be a method by which xyz.com distinguish user A as the same person visiting different pages at xyz.com.

Web analytic tools use cookies to calculate unique visitors.

How a cookie is set ?

Cookies can be set by javaScript or any server sided script.

JavaScript cookie example

Setting a cookie
document.cookie = “COOKIE NAME”+”=”+”COOKIE VALUE”+ “;expires=”+”EXPIRY DATE”+”;domain=”+”DOMAIN”;

COOKIE NAME is a string as a name for cookie, Value is a piece of data, EXPIRY DATE is created by using Date.toGMTString() method of javascript. Expiry value and domain are optional.

Reading a cookie

Reading a cookie is not straight forward. All the cookies set for a domain are available in document.cookie variable as a string. We need to have utility functions to read a specific cookie.

PHP Example

Setting cookie
bool setcookie ( string $name [, string $value [, int $expire [, string $path [, string $domain [, bool $secure [, bool $httponly ]]]]]] )

Reading a cookie

The cookie is directly readable from the $_COOKIE global variable as $_COOKIE[$name]

Same origin policy related to browsers and cookies

In simple terms the explanation of same origin policy would be, if xyz.com sets cookie, only javascript code in a page at xyz.com or a server sided script at xyz.com can only read the cookie. This is a browser policy. If www.xyz.com sets the cookie, the same way only www.xyz.com page js code / server sided script can only read cookie.

Same cookie over all subdomains

If you would like to share the same cookie data across all subdomains of a site, say xyz.com, the domain parameter in a setCookie function should be .xyz.com (dot at the start of the base domain name. No www’s in it !!)

References

HTTP Cookie on WikiPedia

Post a Comment