How to create and read value from cookie ?

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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=/";
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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 "";
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:

  • Creating Cookie:
  • Reading Cookie:

full-stack-img




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.