How to create and read value from cookie ?
Last Updated :
31 Mar, 2020
The web servers host the website. The client-server makes a request for data from the webserver and the webserver fetches the required pages and responds to the client by sending the requested pages. The web server communicates with the client-server using HTTP (HyperText Transfer Protocol). HTTP is a stateless protocol which means the server needs not to retain the user information once the transaction ends and the connection is closed. The web browser is an example of a client-server which communicates with the web server using HTTP. HTTP prevents long engagement of the client with the webserver and the connection is closed automatically once the request is serviced. But often it is required to store the user information for future references. One of the most common uses of cookies is for authentication. Cookies serve the purpose of retaining user information even when the connection is lost. Cookies are data, stored in text files, on the computer.
Cookies comprise of five variable fields:
- Expires:Specifies when the cookie will expire. If left empty the cookie expires immediately when the connection is lost.
- Domain: Specifies the domain name of the website.
- Name=Value: Cookies are stored in the form of name-value pairs.
- Path: Specifies the webpage or directory that sets the cookie.
- Secure: Specifies whether the cookie can be retrieved by any server (secure or non-secure).
However, cookies can store only a small amount of data like
userID or
sessionID. Clearing the cookies will logout the user of every site that it had logged in. HTTP can be made stateful by using cookies. Stateful web applications store the information from the previous requests and can use it for serving future requests.
Working Principle: When the client or web browser establishes a connection with the webserver, the webserver sends some data to the browser in the form of a cookie. The browser may accept or reject the cookie. If the browser accepts it, the cookie gets stored in the hard disk of the client device. The CGI scripts on the server can read and write cookie values that are stored on the client, so when the client visits the same website again it retrieves the cookie data from the browser. JavaScript can be used to manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies for the current web page. The code below demonstrates how JavaScript can be used to create and read a value from the cookie.
Create cookie using JavaScript: This function creates a cookie using the field-name, field-value, and expiry date. The path is left blank such that it applies to the current webpage. However, we can specify any other webpage or directory name.
Program:
javascript
function createCookie(fieldname, fieldvalue, expiry) {
var date = new Date();
date.setTime(date.getTime()+ (expiry*24*60*60*1000));
var expires = "expires=" + date.toGMTString();
document.cookie = fieldname + "=" + fieldvalue +
";" + expires + ";path=/";
}
Read cookie using JavaScript: This function retrieves the cookie data stored in the browser. The cookie string is automatically encoded while sending it from the server to the browser. Hence it needs to be decoded before the actual data can be retrieved. Next, the decoded string is split into an array to get all the cookie name-value pairs. Loop through the array to find the field-name and respective field-values. If the cookie is found, the value is returned else the function returns the empty string.
Program:
javascript
function readCookie(cname) {
var name = cname + "=";
var decoded_cookie = decodeURIComponent(document.cookie);
var carr = decoded_cookie.split(';');
for(var i=0; i<carr.length;i++){
var c = carr[i];
while(c.charAt(0)==' '){
c=c.substring(1);
}
if(c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Create and read cookies using JavaScript: When the webpage is loaded the
runApp() function is called and it checks if there exists a cookie in the browser it is retrieved else a new cookie is created for the same.
Program:
html
<!DOCTYPE html>
<html>
<head>
<title>
Create and read cookies
using JavaScript
</title>
<script type="text/javascript">
function createCookie(fieldname, fieldvalue, expiry) {
var date = new Date();
date.setTime(date.getTime()+ (expiry*24*60*60*1000));
var expires = "expires=" + date.toGMTString();
document.cookie = fieldname + "=" + fieldvalue
+ ";" + expires + ";path=/";
}
function readCookie(cname) {
var name = cname + "=";
var decoded_cookie =
decodeURIComponent(document.cookie);
var carr = decoded_cookie.split(';');
for(var i=0; i<carr.length;i++){
var c = carr[i];
while(c.charAt(0)==' '){
c=c.substring(1);
}
if(c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function runApp() {
var user = readCookie("username");
if(user != ""){
alert("Hello "+user);
}else{
user=prompt("Enter your name: ", "");
if(user!= "" && user!=null){
createCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="runApp()"></body>
</html>
Output:
- Creating Cookie:

- Reading Cookie:

Similar Reads
How to create and destroy cookies in PHP ?
Cookies are used to store the user information in the browser. If you store the cookie in the browser then every time you logged in to the browser then you can log in with the help of stored user information. We can understand this by saying when a user sends the request to the server then the cooki
3 min read
How to read write and delete cookies in jQuery?
In this article, we will learn how to read, write and delete cookies in jQuery. This can be done using the cookie() and removeCookie() methods of the jquery-cookie library. We will first understand what exactly is a cookie.Cookie: Cookies are small blocks of data created by a web server when a user
3 min read
How to get cookies from curl into a variable in PHP ?
The cURL standing for Client URL refers to a library for transferring data using various protocols supporting cookies, HTTP, FTP, IMAP, POP3, HTTPS (with SSL Certification), etc. This example will illustrate how to get cookies from a PHP cURL into a variable. The functions provide an option to set a
2 min read
How to Create Form using CGI script
HTML forms are a fundamental part of web development, allowing users to input data and interact with web applications. Web developers often use Common Gateway Interface (CGI) scripts to process and send the data submitted through these forms. In this article, we'll explain what Python CGI scripts ar
3 min read
How to Disable Cookies on Firefox?
Cookies are small pieces of data stored by websites on your browser to track your online activity. While they can enhance your browsing experience, you might want to disable cookies on Firefox for privacy reasons. Whether you're looking to block all cookies or just manage specific types, this guide
4 min read
How to create a simple CGI script?
In this article, we will explore how to create a simple CGI (Common Gateway Interface) script on a Windows machine but before that, we need some basic ideas about these technologies ( CGI Script, HTTP, Web Server ).CGI Script: A CGI script is a program that runs on a web server and generates dynamic
2 min read
How to set and unset cookies using jQuery?
An HTTP cookie is a small piece of data sent from a server and stored on client-side by the browser itself, Cookies are made to keep track of user and also to provide one nice browsing experience. We can also set our own cookies in the browser according to our need. Cookies can be set in the browser
2 min read
How to create cookie with the help of JavaScript ?
A cookie is an important tool as it allows you to store the user information as a name-value pair separated by a semi-colon in a string format. If we save a cookie in our browser then we can log in directly to the browser because it saves the user information. Approach: When a user sends the request
2 min read
How to create Cookie Consent Box using HTML CSS and JavaScript ?
In this article, we will see how cookies are stored using the cookie consent box using HTML, CSS, & JavaScript.Cookies are small pieces of data that are stored on a user's device while browsing the website. Cookies are used to store information for faster access to data and provide a better user
4 min read
Servlet - Login and Logout Example using Cookies
Cookies are a piece of textual information that is stored in key-value pair format in the clientâs browser during multiple requests. Why do we use cookies?We use Cookies as one of the techniques of Session Tracking / State Management.Session Tracking is a way to maintain state (data) of a user. It i
7 min read