When working with a stateless protocol, where the communication between the web browsers and the assigned servers takes place through the HTTP protocol, commercial websites cannot be used effectively. Websites that require the information entered in one session to be stored in the background for the next session to take place and to repeat this process for the entire process until it is terminated, a proper system is required, and stateless protocol is not the answer. Cookies are used for storing the information entered in a session during a process. This stored data is maintained across the pages throughout the entire process. Cookies also provide a better user experience as the data entered doesn’t get lost, eliminating the need to re-enter the same data again and again.
Understanding the working of Cookies
Cookies function by sending and receiving defined data between the web browser and the visited server. When a web browser is used to access a particular server, the data from the server is sent to the respective web browser; this data is known as cookies, it is up to the web browser to accept and store the received cookies. When the browser accepts the cookies, they get stored on the hard drive of the device on which the web browser is installed. Now, if you visit another page on the site, the stored cookies are sent to the server; this is how the server remembers the input data being entered before visiting the other page.
There are 5 important length fields variable in nature, making text data (plain in composition).
- The first variable length field is expire, this is used to store the expiration information of the cookies. On quitting the browser, the expire field is left blank if the cookie gets deleted.
- The second field variable is a domain; in this field, the site’s domain (or the name of the domain) is stored.
- The third field variable is a path; it is important to remember the information about the web page that stored the cookie on the browser or to remember the path to the directory.
- The fourth field variable is more of a value named secure. If the value is set to secure, then only secure servers can retrieve the cookies, and if no such value is set in the field, then any server is allowed to retrieve the cookies from the browser.
- The form in which these cookies get stored and received is in key form pairs, Name=Value.
CGI scripts are used to read and write cookies stored on the browser, as cookies were initially being developed for programs using CGI scripting. It is an automated process of transferring the stored cookie data between the web browser and the server. You can also deploy JavaScript for the same by making use of the cookie property available in the document object.
Method to Store Cookies
Following are the steps to store a cookie:
Step 1: document.cookie object, make a string value for assigning it to the respective object.
Step 2: Example: document.cookie = “Attempt1 = input1;Attempt2 = input2; expires = date”;
Mentioning the data field is optional. If a particular time or data is specified in the respective field, the cookie will be deleted on the mentioned time or data. The cookie, after getting deleted, will not be available for any further use.
It is important to know that character values such as semicolons, or commas, or any whitespace cannot be included while defining the value of a cookie. But, if you still use them, make sure that you have first encoded the value with the help of escape() function provided by JavaScript. After encoding, you can store the encoded data in the cookie. As the value is encoded now, you can use the unescape function provided by JavaScript to read the value of the cookie before it is encoded.
Following is an example of a JavaScript code applying the above-mentioned functions:
<html>
<head>
<script type = "text/javascript">
<!--
function attemptnumber() {
if( document.examform.student.value == "" ) {
alert("Input attempt number");
return;
}
cookievalue = escape(document.examform.student.value) + ";";
document.cookie = "attempts=" + cookievalue;
document.write ("Setting Cookies : " + "attmepts=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "examform" action = "">
Attempt Number: <input type = "text" name = "student"/>
<input type = "button" value = "set attempt number" onclick = "attemptnumber();"/>
</form>
</body>
</html>
The output for the program is:
Attempt Number: text box; button named “set attempt number”
How to Read Cookies?
It is very simple to read a stored cookie. The value of the cookie can be accessed with the help of the document.cookie object, as the object, when used to encode the cookie, also stores the data of the respective cookie. If you ever require access to a particular cookie, you can simply use the document.cookie object of the respective cookie. As we know, the value of the cookie, when stored in the browser, is stored in the form of name=value pairs. These pairs form a list maintained by the document.cookie object, name=value where the field: name is the name provided to the cookie and the field: value is the string value of the cookie.
Following is an example of a JavaScript code applying the above-mentioned process to read a cookie::
<html>
<head>
<script type = "text/javascript">
<!--
function attemptnumber() {
var examcookies = document.cookie;
document.write ("Exam Cookies : " + examcookies );
// Get all the cookies pairs in an array
cookiearray = examcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key for examattempt cookie: " + name + " and Value for the examattempt cookie is: " + value);
}
}
//-->
</script>
</head>
<body>
<form name = "examform" action = "">
<p> use the following button to read the examform cookies</p>
<input type = "button" value = "total attempts" onclick = "attemptnumber()"/>
</form>
</body>
</html>
The output for the program is:
Use the provided button to call the function
Button display of name total attempts on clicking it will open the exam form cookies.
How to set the expiration time for a cookie?
The expiration time period of a stored cookie can be manipulated with the help of the attribute: expire. The expire attribute can be used to set a particular time or a date for the cookie to expire.
Following is an example of a JavaScript code applying the above-mentioned attribute:
<html>
<head>
<script type = "text/javascript">
<!--
function attemptnumber() {
var timeperiod = new Date();
timeperiod.setMonth( timeperiod.getMonth() + 1 );
cookievalue = escape(document.examform.student.value) + ";"
document.cookie = "final=" + cookievalue;
document.cookie = "expires=" + timeperiod.toUTCString() + ";"
document.write ("Setting Cookies : " + "final=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "examform" action = "">
Input Data: <input type = "text" name = "student"/>
<input type = "button" value = "exam form timeperiod cookie" onclick = "attemptnumber()"/>
</form>
</body>
</html>
The output for the program is:
Use the provided button to call the function
Button display of name exam form timeperiod cookie on clicking it will open the set value of the exam form cookies.
How to Delete a Cookie?
In order to delete a stored cookie, simply set the value of the expire attribute to a date or a time in the past.
Following is an example of a JavaScript code applying the above-mentioned attribute to delete a cookie:
<html>
<head>
<script type = "text/javascript">
<!--
function attemptnumber() {
var timeperiod = new Date();
timeperiod.setMonth( timeperiod.getMonth() - 1 );
cookievalue = escape(document.examform.student.value) + ";"
document.cookie = "final=" + cookievalue;
document.cookie = "expires=" + timeperiod.toUTCString() + ";"
document.write("Setting Cookies : " + "final=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "examform" action = "">
Input Data: <input type = "text" name = "customer"/>
<input type = "button" value = "exam form timeperiod cookie" onclick = "attemptnumber()"/>
</form>
</body>
</html>
The output for the program is:
Use the provided button to call the function
Button display of name exam form time period cookie on clicking it will open the set value of the exam form cookies. The cookie will expire after closing the browser.