Persistent Cookies vs Session Cookies


The main difference between persistent cookies (or simple cookies) and session cookies (or simply sessions) are that cookies are stored in the user's browser, and sessions are not. This difference determines what each is best used for.
“A cookie can keep information in the user's browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie. The trouble is that a user can block cookies or delete them at any time
Sessions cookies are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit.
You can of course get the best of both worlds! Once you know what each does, you can use a combination of cookies and sessions to make your site work exactly the way you want it to.”
I JavaScript it’s very easy to create a cookie. A cookie is actually a name-value pair (e.g. myfirstcookie=hello world) containing actual data stored in the browser. Cookies have an expiry date, path and domain which specifies to which domain the cookie belongs to.
Full example includes:
1.  name-value pair ('ppkcookie2=another test;)
2.  expiration date: expires=Fri, 3 Aug 2001 20:47:11 UTC;
3.  path : path=/
'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i += 1) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x === c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date(), c_value;
    exdate.setDate(exdate.getDate() + exdays);
    c_value = escape(value) + ((typeof exdays === 'undefined') ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}
Adapted from W3Schools example : http://www.w3schools.com/js/js_cookies.asp
The code snippet above includes a method for retrieving a cookie from the browser and adding a cookie to the browser;
Sometimes an application may need to store variables / settings / ids across page while a user is on site. Keeping this data in a cookie can be a security risk, for this reason sessions are very useful for storing temporary settings while the browser is active. A session cookie (session) works much like a cookie, except that it expires as soon as the browser is closed.
NB: The getCookie method above can be used to retrieve session cookies.
    //Session cookie function
    function set_sessionCookie(name, value) {
        String((new Date()).getTime()).replace(/\D/gi, '');
        document.cookie = name + "=" + value + "; path=/";
        return value;
    }
   
    set_sessionCookie('test','hello world');

The above code snippet shows a method sessionCookie that takes as input a session name and value. This value is concatenated to the DOM cookie object. Notice that no expiration date was set in the method above. The last line shows an example of a name-value pair, test that is added. This will be removed when the browser is closed.

Hope this article helped to shed some light on the two types of cookies and how they can be used.

Complete code file below:



/**
 * The following function retrieves a cookie from the DOM cookie obj
 * @param c_name - cookie name
 */
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i += 1) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x === c_name) {
            return unescape(y);
        }
    }
}

/**
 * The following function adds a cookie to the browser
 * @param c_name - cookie name
 * @param value  - cookie value
 * @param exdays - amount of days {numeric} the cookie should expiry in
 */
function setCookie(c_name, value, exdays) {
    var exdate = new Date(), c_value;
    exdate.setDate(exdate.getDate() + exdays);
    c_value = escape(value) + ((typeof exdays === 'undefined') ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

/**
 * Alternative method for retrieving cookie
 * @param c_name
 */
function getCookieTwo(c_name) {
    var ca = document.cookie.split(';'), i, c, y;
    for (i = 0; i < ca.length; i += 1) {
        c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(c_name) === 0) {
             y = c.substring(c_name.length, c.length);
            return unescape(y);
        }
    }
   
    return '';
}


/**
 * The following method sets a session cookie - //Session functions
 * @param name - session cookie name
 * @param value - value
 */
function set_sessionCookie(name, value) {
    String((new Date()).getTime()).replace(/\D/gi, '');
    document.cookie = name + "=" + value + "; path=/";
    return value;
}


Comments

Popular posts from this blog

JavaScript Module Pattern: 2 Forms

Pseudo-Random UUID Generation with mask support

Mocking Ajax with the JQuery Mockjax Library