0
3.2kviews
What is the need of cookies? How can cookie be used to set up a counter which shows number of time the user has visited the page?
1 Answer
0
56views

Cookies

  • A cookie is a piece of data which is sent from a website and stored locally on the user’s browser.
  • Common uses for cookies are authentication, storing of site preferences, shopping cart items, and server session identification.
  • A cookie created by a user can only be visible to them. Other users cannot see its value.
  • The size of a cookie dependent on a bowser. In general, it should not exceed 4KB that the web server stores on the client computer.
  • Cookie has several attributes, such as
    • name – Name of the cookie in the key-value format.
    • expire – Specify the date cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
    • path – Specify server path in which the cookie will be available.
    • domain – Shows domain the cookie is available. Domain name of site.
    • secure – If set true, the cookie is available over a secure connection only. The default value of this attribute is false.
    • httponly – If set true, the cookie is available over HTTP protocol only.

Need of cookie

  • Cookies are needed because HTTP is stateless. This means that HTTP itself has no way to keep track of a user’s previous activities. One way to create state is by using cookies.
  • A cookie is generally used to store the username and password information on a computer so that user need not enter this information each time when visits a website again.
  • Cookies are a convenient way to carry information from one session on a website to another, or between sessions on related websites, without having to burden a server machine with massive amounts of data storage.

Example

<SCRIPT LANGUAGE="JavaScript">
<!--
var now = new Date();    // create an instance of the Date object
fixDate(now);    // fix the bug in Navigator 2.0, Macintosh
/*
cookie expires in one year (actually, 365 days)
365 days in a year
24 hours in a day
60 minutes in an hour
60 seconds in a minute
1000 milliseconds in a second
*/
now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
var visits = getCookie("counter"); // if the cookie wasn't found, this is your first visit
if (!visits) {
  visits = 1;     // the value for the new cookie
  document.write("By the way, this is your first time here.");
} else {
  visits = parseInt(visits) + 1;      // increment the counter
  document.write("By the way, you have been here " + visits + " times.");
}
setCookie("counter", visits, now);      // set the new cookie
// -->
</SCRIPT>

This script can be placed anywhere on the web page. It prints the number of times the user has visited web page.

Please log in to add an answer.