Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

Making cookies

A cookie is a small one-line file that is written to the client's machine. Cookies allow a web author to restore the state of a web page when the user revisits. For example if you go to a web page and fill out your name in a text field then close the web browser then go back to the same web page your name could reappear in the same text box without your interaction.

The following example is going to show you how easy it is to make cookie. Truly it is easy but only if you have fully documented source code. There are three things you do with a cookie, one, make it, two, read it and three, delete it. Place note this document is not going to tell you how to eat a cookie.

The following example is going to make a cookie hit counter that is for every time the user goes to the web page the counter gets incremented by one. This information is written and read to and from a JavaScript cookie file. This information will be alerted to the user with the alert method. This application will also give the user the opportunity to reset the hit counter which clears the history of the user as if they never came to the web page.

To achieve our goal were going to make three cookie functions and one function utilizer:

  1. Make the cookie
  2. Get the cookie
  3. Delete the cookie

The function utilizer is called addHit. This function is made to use the make and read cookie functions it is called every time the document loads. Run Code | View Code

Process

Events

Input

The value retrieved from the read cookie function

Event Trigger

The onload event of the document will call the readCookie function that will try to read the value from the hits cookie. If the cookie was not made the makeCookie function is called that makes it, then the total number of hits is alerted. If the user clicks the "do not remember my user name any more" button the cookie is deleted and the hits cookie is deleted.

The Solution

Define form elements

<form>
Make the Delete the cookie file button call the deleteCookie function and pass the cookie counter as the argument <input type="button" value="Delete the cookie file" onclick="deleteCookie('counter')"> Make a convenience button to reload the document (This will increase the number of hits by one) <input type="button" value="Reload" onclick="window.location.reload()">
<form>

Define the body element

Make the onLoad event of the document call the addHit function <body onload="addHit()">

Define addHit

Function analyses

The addHit function's purpose is to increase the number of times(hits) the user came to this web page by one. This function uses the read cookie and make cookie functions to do it's job.

It declares hits local variable to the value returned by readCookie. readCookie returns the value of a cookie named counter. If the counter cookie was not found readCookie returns null. This function then checks if hits is null if it is not it means the cookie was created before otherwise it wasn't.

If the cookie counter was not created it makes it by calling the makeCookie function. It passes it counter as the name of the cookie and zero (0) as the value since that's going to be the initial value of the counter to be started at and finally 365 for the expiry date which of course is one year at which the cookie will expire.

After make cookie is called a cookie named counter is created and set on the document.cookie property.

If the cookie was created before the parseInt function is used to turn hits in to a numeric value. Once this is done it is possible to increment the value by 1 using the += operator. Finally a cookie with the same name and expiry date is created when calling the makeCookie function but this time the incremented value is passed as the value argument.

Comments with code

function addHit(){
Call readCookie and pass it counter and put the returned value into hits var hits = readCookie("counter") The cookie does not exist if(hits == null){
Make a cookie with the name counter with a value of 0 that will expire in one year makeCookie("counter",0,365) Show an alert stating that it's the first time the user has come to this page alert(This is the first time you have been to this page") A cookie with the name exists
}else{
Call make cookie again and pass it the same name and the value it was plus one makeCookie("counter",hits,365) Increase hits by one hits = parseInt(hits) + 1 Show the alert alert("You have visted this page " + (hits) + " times")
}
}

Define ReadCookie

Function analyses

Read cookie gets the cookie with the specified name out of the available cookies. If the name does not exist null is returned.

The readCookie function must search the value inside document.cookie. If you make a cookie and set it onto document.cookie (with a different name) that new cookie is appended onto the last cookie. Each cookie is delimited by a semi colon and each name/value pair is also delimited by one. This function takes this fact into account for it to get the value for the name out of this difficult to read string.

To understand this function's processes you must understand the substring and indexOf method of a string.

The function first gets the value from document.cookies and inserts into the c variable [var c = document.cookie]. Then it performs a search for given name var [start = c.indexOf(name + "=")], if the name is not found the function returns null and exits.

Otherwise the function tries to get the value for the given name. As the indexOf method returns the index of the name the function can then try and get it's value.

Two things must be achieved to get the value out of the c string:

  1. find the starting point of the value
  2. find the ending point of the value

Well we are already half way through the first step we know the starting position of the name but what we want is the starting point of the name's value. Since the value begins straight after the name it is easy to get the value. All that's done is that the starting position is increased by the length of the name and since there is always an equal sign (=) between the name/value pair the starting point is increased by one more. Ha! We got the starting point of the value for the given name, step one is complete!

start+= name.length+1

it's good that we have the starting position but we need the ending position too. Otherwise if there are other cookies in this cookie and they are pass this cookie they will also be returned as the value.

To get the ending index the semi colon (;) character is searched for, not any semi colon but the first one straight after the starting position of the value. (The starting position was worked out above). A semi colon is searched for because it is known that there is a semi colon delimiter straight after the value. As there are lots of semi colons in a cookie we search for the first one, that is the one after the starting position. If there is no semi colon it means there are no other cookies in this cookie, it also means the end of the cookie file was reached.

var end = c.indexOf(";",start)

If the end of the cookie file was reached (There are no other cookies) All text from the starting position to the end of the cookie file is returned. This means the end position is not needed and not used.

return c.substring(start)

But if the end position was determined (The cookie file has more then one cookie) the value between the starting position and the end position is returned. The end position must be used so all other data pass the end is ignored, since it is not required and is not part of the value.

return c.substring(start,end)

Comments with code

function ReadCookie(name){
Get all the cookies associated with this document var c = document.cookie Search for the name of the cookie var start = c.indexOf(name + "=") No cookie with that name found , terminate this process if(start == -1) return null Move the start position to the end of the name and the = sign start+= name.length+1 Search for the end position starting at start index var end = c.indexOf(";",start) end was found if(end != -1){
set v to the string between start and end v = c.substring(start,end) No end found
}else{
set v to everything after start var v = c.substring(start)
} Return the value return v }
}

Define MakeCookie

Function analyses

The make cookie function makes a cookie according to the cookie specification. The minimum requirements for this function to work are the name and value of the cookie. The Days argument is necessary if the cookie should exist beyond the current session.

This function first checks if the name or value argument is null if it is the function quits because these two arguments are necessary to make a cookie.

Otherwise it sets express to nothing then checks if the days argument was given. If it was it makes an instance of the date object and sets it's time to the current time and adds the current time to the total number of days given (converted to seconds in a day then changed into milliseconds). This gives the expiry date for the cookie. The expiry date is finally converted into the correct string representation for a cookie by using the toUTCString method. Once the expiry date is known it then formats the name/value pair for the expiry date and sets that into the expiry variable.

If path, domain or secure are given their name/value pairs are formatted according to the cookie format. Otherwise they are set to an empty string rather then undefined. This is also true for the date argument. Hence they are all optional.

After the cookie is formatted correctly it is appended to the cookie list contained in cookie property of the document object.

Note as the cookie format states each name/value pair must be delimited with a semi colon.

Comments with code

function makeCookie((name,value,days,path,domain,secure){
If name or value is nothing if(name == null || value == null){
terminate this process return
} By default expires is not set var expires = "" If days is not null if(days){
Create a new date var date = new Date() Get todays date var toDay = date.getTime() Add todays date to the number of days this cookie should expire expires = toDay + (days * 24*60*60*1000) Use the setTime method and pass it expire date date.setTime(expires) Get the correct cookie date represenation expires = date.toUTCString() format the expire's name/value pair and dimlinter it by a sec";" expires = ";expires=" + expires
} format the path's name/value pair path = (path != null) ? ";path="+path : ";path=/" format domain's name/value pair domain = (domain != null) ? ";domain="+domain : "" format secure' name/value pair secure = (secure != null) ? ";secure="+secure : "" append this new cookie to the document.cookie property document.cookie = name + "=" + value +";" + expires + path + domain + secure
}

Define deleteCookie

Function analyses

The delete cookie function's purpose is to remove the specified cookie from the client's system.

Path and domain are optional. If the domain is provided the cookie will only be deleted if the domain matches the domain in the cookie the same is true for the path argument. The name argument is necessary, it represents the name you used to set the cookie.

Only one line of code is necessary to delete a cookie since the saveCookie's function is called and is passed the same parameters you pass this function. As you may have noticed this function does not need a date parameter that is because the date is the key to delete a cookie. When making a cookie you set the expiry date on it to keep it alive but here we want the cookie to be terminated! To do this the expiry date is set to -1 this will terminate it, since it will cause the date attribute of the cookie to be one day out of date therefore the browser will remove it.

Comments with code

function deleteCookie(name,path,domain){
Call the save cookie function and pass it -1 for the days parameter makeCookie(name,"",-1,path,domain)
}

Cookie format

Maybe cookie should be called cookies because a cookie can contain more then one cookie.

A cookie is a set, retrieved and deleted by manipulating the cookie's name-valued pair segments.

A name-valued pair contains the name of the cookie and it's value and any other optional arguments that a cookie can have. Each argument is also considered to be a name value pair. After every value a semi colon is added.

The optional arguments are expires, path, domain and secure. The name is the part of the cookie that referredto the value. The value is the part that holds the actual data of the cookie. As you may have guessed name and value are required.

Although Expiry date is an optional parameter if not set on the cookie will die (be deleted) as soon as the web browser is closed). See Expiry date section.

Every document has it's very own document.cookies property.

The cookie format looks like this:

CookieName = cooikeValue [;]
expires = date[;]
path=path[;]
domain=[domain];
secure = [false];

For example:

"xPos= 100; expires =date; path=/test; domain=yahoo.com; secure = false;"

If there were two cookies set, document.cookie would like:

"xPos= 100; expires =date; path=/test; domain=yahoo.com; secure = false;" "yPos2=200;expires =date;path=/test;domain=yahoo.com;secure = false;"

If you want to see if a document has cookies attached to it try alert the cookie property like this:

alert(document.cookie)

Cookie Usefulness

Cookie can be used to:

Cookies in the real world

This story describes how useful cookies can be by analyzing the yahoo.com login email system. Yahoo remembers the username and the password to make a better user experience. The password is stored temporary but the user named is stored for good.

If the password was to be remembered for a long time it may give a different user time to log into the clients email account and use it at will. Therefore Yahoo.com only remembers the password for about 3 minutes. This makes it more difficult for another user to squeeze through the gaps. Yahoo goes through all this trouble to give the client a better browsing experience. If you want to increase user satisfaction you would do a similar thing.

Yahoo remembers this small amount of information in cookie to make it so the client doesn't have to keep retyping their user name every time they go to the web site. Yahoo cannot use a server side session to do this because it is impossible to know what client is calling therefore how would yahoo show the correct name for the calling client? This is a good time for a cookie do not you think so? It is safe, it is the only way to remember the information, If the cookie gets deleted it doesn't matter because yahoo has the information backed up in a database and it is an extra benefit that will increase user satisfaction. If the user turned off cookies it's only going to make them retype their name at their own expense.

Therefore cookies have a time and place to be utilized.

When to use cookies?

When The information: Is Good to have but not necessary

As the user can delete the cookie at any time or disable cookies completely you shouldn't rely on the cookie to make the web site function properly. This means you should make the information accessible from another source if the information is mandatory. For example you shouldn't store information like the user's name and email address in a cookie and only rely on that you need a backup plan, which is a database. Therefore if the cookie gets deleted it doesn't matter because the information can be recovered from the database.

The information is good to have from the user's point of view because they do not have to keep retyping their username. However If the cookie got deleted, disabled or expired the only thing that will happen is inconvenience for the user (They have to retype their username). This does not effect the rest of the system since the information from the cookie is not necessary since it is backed-up else were.

When The information: Is not to lengthy

You shouldn't store large chunks of text in a cookie such as comments about a web site taken from a text area because there is a cookie size and total cookie limitation

See size and total cookie limitation in downfalls

When The information: Is not a security risk

do not store information like passwords in a cookie if it is used to get into a paid or restricted web site. because the user can open the cookie file and see it's contents

When The information: Must be displayed without having the user to provide information.

To display information without having the user provide any information is the true benefit of a cookie. This allows a web page to automatically customize itself for a specific user as soon as they arrive! A session object on the web server cannot achieve this because there is no way for it to know who and what client is calling. A session must be given information before it can begin tracking the user and any server side scripting language cannot automatically customize a page for a specific user for the same reason but a cookie can!

For example a user visits the same web page twice. The first time they visit they provide the user name and allow the cookie to be saved. The second time and all remaining times they go to the same web page the cookie file can be read and the username can be set into a username text field.

Downfalls

Security risk

Same people do not like to use cookies because the client can open the cookie and see it's contents. However in most situations the average user cannot understand it's consents and this may be also true for some computer experts because the data in the cookie is only understandable by the creator of it.

As the saying goes it's best to be safe then sorry therefore do not put any information in a cookie that is sensitive in the first place!

Deletion

The user can delete your cookie at any time therefore do not put any information in them that must be extracted to restore the web page.

Disabled cookies

The user can disable cookies by turning off cookies in their web browser. Therefore if you try and make one it won't be made.

Size and total cookie limitation

Information that is inserted into a cookie must not exceed 4 kilobytes which is about 4442 characters. 300 cookies are allowed however only 20 cookies can be set on the same domain. For example yahoo can have 20 cookies at yahoo.com and another 20 at mail.yahoo.com. If the 20 cookie limit has reached the last cookie added is deleted. If the cookie is larger then 4 kilobytes the cookie is transacted cutting off the information at the point where it exceeds the size limit.

Note: This information is subject to Netscape Navigator web browser.

Who Uses Cookies?

What web site has access to what cookies?

Cookies can only be accessed by the web site that created them. This cookie behavior is implemented by the web browser. The browser will only allow you to read a cookie that was made by the same web site. For example if yahoo makes a cookie Microsoft can't read that cookie vice-versa

Expiry date

A cookie's life

A cookie's life is determined by the expiry date set on it. If an expiry date is not set on a cookie the cookie will die (be deleted) as soon as the web browser is closed therefore if you want the cookie to exist for a longer time then this you must set an expiry date on the cookie.

Expiry Date format

The cookie date format doesn't even have to be known because JavaScript provides the method toUTCString that returns this format. However if you are interested read it.

Wdy, DD-Mon-YYYY HH:MM:SS GMT

where:

wdy - is a string value stating the whole day. eg Monday
DD - is a integer value stating the day of the month. eg: 09
YYYY - is a integer value stating the year. eg: 99
HH - is a integer value stating the hour. eg: 04
MM - is a integer value stating the minute. eg: 02
SS - is a integer value stating the second. eg : 10

for example:

Wednesday, 09-Nov-99 23:12:40 GMT

Setting cookie's expiry date

To set an expiry date on a cookie you use three methods of the date object

First you use the getTime method to get the current time.

currentTime = date.getTime()

Now that you have the current time you use the setTime method and give it the current time plus the amount of time the cookie should die. Lets say we want the cookie to be terminated in two days. Therefore you would write:

Date.setTime(currentTime + 24*60*60*1000*2)

As you may have noticed we take the current time and add 24 and then times it by 60 twice. The result will give the total number of seconds in a day. After the total number of seconds is known, it is multiplied by 1000 because we are working milliseconds. Once the total number of milliseconds in a day is calculated it is finally multiplied by 2, 2 meaning two days. If you want the cookie to be terminated in three days just change the 2 to a 3.

The second last step is two convert the date into the format required by a JavaScript cookie. To perform this you simply use toUTCString method. This method returns the corect format for a cookie date.

CookieFormatExpiryDate = date.toUTCString()

Finally you set this expiry date segment along with the other parameters on the cookie property of the document.

Cookie parameters

There are six parameters you can use when making a cookie:
NameValueExpiry DatePathDomainSecure
Purpose The name that is used to get the cookie's value The actual data that is stored and retrieved by the name The day at which the cookie will die (be deleted) The Path of the cookie The domain of the cookie Detemines if a secure network chancel is required either HTTP or SSL
Required YesYesNoNoNoNo
Data type StringStringDateStringStringBoolean

Optional Parameters

The following three parameters are optional.

They determine if a client side script can read the cookie. Their function is also to allow or disallow the cookie to be transmitted to the server requesting it.

Path and Domain

Path and domain if set determine if the cookie is sent. Domain is checked first. If a match is found then the path is checked. If both path and domain are satisfied the cookie when read is allowed.

Path and domain if set can decrease the amount of network traffic sent to the server because the cookie is not sent if the path and domain do not match. Therefore unnecessary cookies are not sent.

Path and Domain give a server side scripter confidence in that they are getting a cookie they made. If the path and domain match a portion of the URL of the calling document the cookie is sent when requested otherwise is isn't.

What does a match mean?

When talking about matching a path or domain it means a portion of the URL of the document is the same as the URL in the cookie file.

For example if a cookie is made with the domain yahoo.com with a path of /email. The cookie will only mach this path and domain if the web browser window is currently located at http://yahoo.com/email

Secure

A secure network means the server and client both uses one of the mentioned secure protocols. If a secure network is required and it isn't, the cookie is not sent.

Run Code | View Code

See also: Getting the time | Prompt method


Using alert | Using the status bar | Changing the background color of the document | Changing the content of a document | Using prompt | Using confirm | Changing the URL of a window Manually | Querying a text field's value | Checking the selected value of a select object | Checking if a checkbox is selected | Checking if a radio button is selected in a group | Making a rollover | Preloading images | Getting the time | Using setTimeout/setInterval | Making windows

JavaScript Tutorial Home