Cookies L1
Cookies L1
• Basics of cookies
• Creating cookies
• Reading a cookie value
• Setting expiration date of cookies
• Deleting cookies
BASICS OF COOKIES
• Cookie is a small piece of information that a website writes to your hard
disk when you visit the site
• The browser then stores it in the user’s computer and sends it back to
the same server in the next requests
• A java script can be used to create cookies whenever someone visits the
web page that contains the script
• A java script can also be used to read the cookies stored on user’s
computer, and it uses the information stored in cookies to personalize
the web page that a user visits
• Some developers store user ID and password data to a cookie after a
user successfully logs on to their web site
• The cookie is then used for subsequent logons
BASICS OF COOKIES
• The text of cookie must contain a name-value pair
• Cookies come in two flavors: session cookies and persistent cookies
• Session cookie resides in memory for the length of the browser session
• A Persistent cookie is a cookie that is assigned an expiration date
• A persistent cookie is written to computer’s hard disk and remains there
until the expiration date has been reached
• Each cookie contains the address of the server that created it
• You can store only 4 kilobytes of information into cookies
• Browser software will usually not retain more than 20 cookies per web
server
CREATING A COOKIE
• You can simply assign the cookie to the window.document.cookie object
• The browser automatically writes the cookie to memory when it reads
this assignment statement
• Cookie is written to computer’s hard disk only when you set an
expiration date for the cookie
• Every cookie has four parts: a name, an assignment operator, a value
and a semicolon
• E.g.
window.document.cookie = “username= XYZ;”
READING A COOKIE
• The value of the window.document.cookie object is cookie
• When the browser sees window.document.cookie statement within a
java script, it copies the cookie to window.document.cookie object
• You can then use window.document.cookie whenever you want to
access the cookie
SETTING EXPIRATION DATE OF COOKIES
• You can extend the life of cookie beyond the browser session by setting
an expiration date and saving the expiration date within the cookie
• The expiration date is typically increment of the current date
• This can be done by setting the ‘expires’ attribute to a date & time
DELETING A COOKIE
• Cookies are automatically deleted when either the browser session ends
or its expiration date has been reached
• However, you can remove cookie at any time by setting its expiration
date to a date previous to current date
• This forces the browser to delete the cookie
• E.g.
d.setDate( d.getDate( ) – 1 );
document.cookie = “expires=“ + d.toUTCString( );