Cookies and tracking user information

Try this quick little demo, as it shows you how easy it is store information with cookies in JavaScript. We have seen how to use cookies and session variables in PHP. There are a few big differences though between cookies and sessions,

What are these things?

Cookies are used to store information on the browser. This is data that the webserver wants to know about, but will not store internally. There are quite a few use cases for this. We could store information that records who you are, such as an authentication token. It is also useful for pages that use shopping carts, and in a very common use case to track you across websites (3rd party) to support ads.

Storing Cookies

In JavaScript, cookies are defined within a string, such that:

To make our life a bit easier, we can use a function similar with the one from w3schools. Don't forget to "escape" the values, which will replace any special character (such as ; or space) with their equivalent URL encoded code.


            // Create cookie with name specified by 'identifier' with value 'value'
            // If 'days' is set, sets to expire 'days' days from now.
            function createCookie(identifier,value,days) { 
                if (days) { 
                    var date = new Date();
                    date.setTime(date.getTime()+(days*24*60*60*1000));
                    var expires = "; expires="+date.toGMTString(); 
                } 
                else 
                    var expires = ""; 
                                                                                                                
                document.cookie = identifier+"="+escape(value)+expires; 
           }                                                                                                                       } 
              

Accessing Cookies in JavaScript

Cookies can be accessed in JavaScript via the document.cookie property, which will return all cookies for the page in a string like

cookie1=value1; cookie2=value2; cookie3=value3
In order to access cookies in JavaScript we need to break apart the document.cookie string. We can use the following function:

            // Return the 'value' of the cookie variable with name 'desiredId'
            // returns null if no match found.
            function readCookie(desiredId) {
                    var cookies = document.cookie;

                    // First split the pairs apart on '; '
                    var pairs  = cookies.split("; ");

                    // Now split each pair on '='.  Check if have a match
                    for (var i=0; i < pairs.length; i++) {
                        var aPair = pairs[i];
                        var cookieTokens = aPair.split("=");
                        var id  = cookieTokens[0]; 
                        var value = cookieTokens[1];
                        if (id == desiredId) {
                            // found desired variable -- return value
                            return unescape(value);
                        }
                    }

                    return null;   // no match;
             }
            

Deleting Cookies

To delete a cookie we need to set it to expire in the past, since we already have a createCookie function, we can use that again just with a date in the past:


            function eraseCookie(cname) {
                 createCookie(cname, "", -1);
            }

Cookies are for everyone

Remember, all relevant cookies are sent by the browser to the server.

This allows both JavaScript and PHP to see the same information, and as a reminder, this would be a good place to store information (such as the user's first name, an authentication token, or other information that both would need access to.) But... remember that cookies are stored on the client side, so they can be manipulated by the user. It would be wiser to store more sensitive information within the server via Sessions.

Practice Problems

  1. Ask user for favorite quote using a window prompt. Save quote in a cookie identified by “favQuote”. Display quote on the page.
  2. Read the value of a cookie named “favQuote”. Display it in a pop-up message if it exists, otherwise ask the user for their favorite quote using a window prompt, save the quote in a "favQuote" cookie, and display the new quote.