Saturday, June 19, 2010

Difference between cookies and sessions

As far as my knowledge is concerned, cookies are stored on client side where as sessions are server variables. The storage limitations are also there (like IE restricts the size of cookie to be not more than 4096 bytes). We can store only a string value in a cookie where as objects can be stored in session variables. The client will have to accept the cookies in order to use cookies, there is no need of user's approval or confirmation to use Session variables cos they are stored on server. The other aspect of this issue is cookies can be stored as long as we want(even for life time) if the user accepts them, but with session variables we can only store something in it as long as the session is not timed out or the browser window is not closed which ever occurs first.

Coming to usage you can use both cookies and session in the same page.

We should go for cookies to store something that we want to know when the user returns to the web page in future (eg. remember me on this computer check box on login pages uses cookies to remember the user when he returns). Sessions should be used to remember something for that particular browser session (like the user name, to display on every page or where ever needed)

Cookies
- stored on CLIENT machine
- amount of data to be stored is LIMITED
- it can only store STRINGS
- quite FASTER than a session

Session
- stored on SERVER machine
- amount of data to be stored is NOT LIMITED
- it can store OBJECTS
- quite SLOWER as compared to cookies

Sessions: are basically tokens which are generated when a
user proceeds with a login mechanism. Each time when a user
logged into a website a new and unique token is generated
and it will destroyed whenever he/she logged out from that
site or power goes off. However, session information is
temporary and will be deleted after the user has left the
website.

Cookies:are temporary files which are store in users hard
disk. A cookie is often used to identify a user. Suppose a
user enters into a website and without logging off he/she
closed the page, next time when he/she open the page he/she
found himself/ herself logged in. This is because of
cookies, they store the user information. We can set the
cookies by setCookie() function. The syntax if
setCookie function is setCookie(name, value, expire,
path, domain);
.

No comments: