Cookies


Cookie is probably one of the most interesting development for the HTTP.
Cookies are small text files generally not larger than 8 kbs (I’m still exaggerating). These NOT downloaded from the web. They are saved by the Browser (yes the browser, your own client). The cookie is saved when server directs the browser.

The Server sends a response header of Set-Cookie

Set-Cookie: favColor=blue; expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=example.com

This above response header is parsed by the browser, and the text file is saved for that domain, in this case “example.com”

To set the cookie (at server end) you need to use the interface the language gives you. eg in php…

setcookie(“favColor”, “blue”, time()+(24*3600), “/path1/”, “example.com”);

This will set the cookie favColor with value blue which will expire in 1 day for path “path1/” and domain “example.com”

The main data in the cookie is the name=value pair, favourite color = blue. There are other attributes for a cookie.

  • Expiry Date: This is the date when the browser should delete the cookie from the file system.
  • Path: The virtual directory path for which the cookie is valid.

I’ll explain the path,
Consider that you have http://www.example.com/path1/ and http://www.example.com/path2/.
If you save your cookie with path=/path1/ , then the cookie won’t be visible for http://www.example.com/path2/* Which means any directories/files in path2 and path2 itself won’t be able to access the cookie. If you set path=/ then the cookie is available everywhere in example.com

You must be wondering how is the cookie that is saved on the client side is “visible” to the server !! ? The answer is that for every HTTP request, the browser send the Cookie header, In which data is sent back to the server. The request header looks like this.

GET /path1/ HTTP/1.1
Host: example.com
Cookie: favColor=blue; otherName=otherValue

Now the Server Scripting Engine parses the header and saves in whatever variables. eg in PHP it saves in $_COOKIE variable

$_COOKIE[‘favColor’] = ‘blue’;
$_COOKIE[‘otherName’] = ‘otherValue’;

Guys who have read through this … till this end have a great advantage when in an interview😉

One Response to “Cookies”

  1. GET / HTTP/1.1 » Blog Archive » Multiple Domain Logins Says:

    […] If you take a look at the other post about Cookies Note the parameter domain it is this parameter that you need to use. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: