Web Cookies

HTTP Cookies

What are Cookies?

Cookies are small amounts of data associated with a domain and stored on the client's machine via the browser.

Cookies are used for a variety of tasks:

The main use is in session identification, but it should be remembered that session can also be controlled by the URL (Uniform Resource Locator) either directly in the URL or via the Query String. Some even try to use form post submission to control state Cookie session control is perhaps the easiest and least intrusive to apply though. Though, HTTP authentication is not a bad way to control state.

Some people dislike the use of cookies that are employed for visitor tracking, though if you have a static IP (Internet Protocol) number, and unless you are using a proxy your visits, your site visits can still be tracked.

Cookies can be turned off in most browsers, but you may find it hard to use a lot of sites. Another approach is to set the browser to remove all cookies when it is closed.

When using a public terminal it is important to remember to clear cookies if you have logged into any site that contain sensitive data. It is quite possible to log into a site, browse other websites and then walk away from the terminal leaving yourself logged into the first site, for the next person to use the terminal to discover.

Cookies can be set and read either on the client side using JavaScript, or set and read on the server side via the web server or an application that can control the flow of data through the web server.

Cookies are often handled by the CGI (Common Gateway Interface) on the server side, to an application which can be written in a variety of languages; Perl, Python, C, PHP and Java are the common ones.

Cookies actually form part of the HTTP request cycle, and are transmitted back and forth with every request to the corresponding domain.

Cookies send name=value pairs separated by semicolons, following the data payload are four attributes:

To delete cookies the expires date is often set to a date in the past, normally one or two days is taken from the current date to achieve this.

To set a cookie to expire when the user closes the browser (a cookie that lives only for the session) then do not supply an expires date.

The secure parameter is used to mark a cookie that should only be sent over a secured (encrypted) channel, such as https.

Lou Montulli is credited with coming up with the idea of HTTP cookies, whilst he was working at Netscape on an ecommerce project. The term cookies though, comes from the idea of magic cookies, which is used to describe data that is sent and then only read again by the sender.

Cookie Limits

There are some guidelines as to how many cookies should be stored by the browser and the maximum size a cookie should be:

These are just guideline and browsers do vary as to what they will accept.

Because of the 20 cookies max per domain, multiple preference values are often stored in one cookie.

Client Side Cookies (JavaScript)

Cookies originally were created and accessed on the server side. When JavaScript appeared though, cookie handling on the client side became a reality.

It is probably not advisable to set session control cookies using JavaScript, but JavaScript preference cookies are a good candidate.

Showing, and perhaps manipulating at the user's behest, server side set session control cookies using JavaScript, though is a nice touch to add to a website.

Cookies are set and read using the document.cookie object.

Setting Client Side Cookies

Setting a cookie is simply a matter of assigning a correctly formated cookie string to document.cookie. document.cookie appends the cookie information, so setting another cookie does not overwrite the first.

function setCookie() {
    // set cookies

    var exp = new Date();

    exp.setDate(exp.getDate() + 2);

    var cookie1 =
        "cookie1=" +
            escape("test1 cookie")     + "; " + // data
        "expires=" + exp.toGMTString() + "; " + // expires
        "path=/cookies";                        // path

    document.cookie = cookie1;

    var cookie2 =
        "cookie2=" +
            escape("test2 cookie")     + "; " + // data
        "expires=" + exp.toGMTString() + "; " + // expires
        "path=/cookies";                        // path

    document.cookie = cookie2;
}
//----------------------------------------------------------

When dealing with cookies, it is often useful to roll your own cookie handling function.

function cookieSet(
    name, value, lifespan, path, domain, secure) {
    // set an arbitary cookie

    if (name == null || name == "")
        return;

    if (value == null || value == "")
        return;

    if (lifespan == null || isNaN(parseInt(lifespan)))
        lifespan = "";

    var cookieStr = name + "=" + escape(value) + "; ";

    if (lifespan != "") {
        var exp = new Date();

        exp.setDate(exp.getDate() + lifespan);

        cookieStr +=
            "expires=" + exp.toGMTString() + "; ";
    }

    if (path)
        cookieStr += "path=" + escape(path) + "; ";

    if (domain)
        cookieStr += "domain=" + escape(domain) + "; ";

    if (secure)
        cookieStr += "secure";

    document.cookie = cookieStr;
}
//----------------------------------------------------------

If JavaScript is enabled in your browser you should see a form below that will allow you to set cookies in your browser.

Reading Client Side Cookies

Reading cookies in JavaScript is just a matter of reading from the document.cookie object. The split function is used to separate the cookies.

function readCookies() {
    // read and display browser cookies

    var out = document.getElementById('cookiesOut');
    var p   = document.createElement('p');

    var txt1 = document.createTextNode(document.cookie);

    p.appendChild(txt1);
    p.appendChild(document.createElement('br'));

    var cookies = new Array();
    cookies     = document.cookie.toString().split('; ');

    for (var k =0; k < cookies.length; ++k) {

        var pair = new Array();
        pair     = cookies[k].split("=");

        var txt = document.createTextNode(
            pair[0] + " : " + unescape(pair[1]));

        p.appendChild(txt);
        p.appendChild(document.createElement('br'));
    }

    clrEle(out);

    out.onclick      = readCookies;

    out.style.cursor = "pointer";

    out.appendChild(document.createTextNode(
        "Click to Re-read Cookies"));
    out.appendChild(br());

    out.appendChild(p);
}
//----------------------------------------------------------

Server Side Cookies

Cookies are sent and received in the header section of the HTTP request.

To set a cookie on the server side, a correctly formated cookie value is inserted in the header of the data that is sent.

To get a cookie on the server side, the browser sends any appropriate cookies in the GET request header.

Cookies with Perl

Cookies can be set and read, by printing custom headers, or examining environment variables, but Perl has a fairly standard module CGI that makes things a little clearer.

Setting Cookies in Perl

The CGI module offers the cookie object, that can be used to set cookie values and parameters. When the cookie has been made it is included in the header.

#!/usr/bin/perl -w

use CGI qw(:standard);

use strict;

my $expire = gmtime(time() + (365 * 24 * 60 * 60)) . " GMT";

my $cookie = cookie(
    -NAME    => "testcookie1",
    -VALUE   => "perl cookie",
    -EXPIRES => $expire);

print header(
    -COOKIE => $cookie);
#-----------------------------------------------------------

Reading Cookies in Perl

The CGI module offers an easy way to read the cookies sent from the browser.

#!/usr/bin/perl -w

use CGI qw(:standard);

use strict;

my $cookie = cookie("testcookie1");

print header();
print start_html("Cookie Test");
print h1("Cookie is : " . $cookie);
print end_html();
#-----------------------------------------------------------

Cookies with Python

Python, in web development, is often used in conjunction with an application server, which tend to offer bespoke ways of handling cookies. Though, Python of course has all the basic libs to handle cookies directly.

Setting Cookies in Python

The Cookie module offers a number of different Cookie objects to assign to aid in setting cookies.

#!/usr/bin/python

import Cookie

cookie = Cookie.SimpleCookie()

cookie["pythonCookie"] = "Test Python Cookie"

print cookie
print "Content-type: text/html\n"
#-----------------------------------------------------------

Reading Cookies in Python

Cookies are placed in the environment, can be accessed from there, and then split into their name value pairs.

#!/usr/bin/python

import os

cookies = None

if os.environ.has_key('HTTP_COOKIE'):
    dough = os.environ['HTTP_COOKIE']

    cookies = dough.split(";")

print "Content-type: text/html\n"

print """<html>
<head>
<title>Cookies from Python</title>
</head>
<body>
"""

if cookies:
    for cookie in cookies:
        print cookie
        print "<br />"

print """</body>
</html>"""
#-----------------------------------------------------------

Cookies with PHP

PHP is of course web centric, so perhaps has the simplest method of dealing with cookies.

Setting Cookies in PHP

setcookie inbuilt function is used to set cookies.

<?php

setcookie("PHPcookie", "test PHP Cookie");

//----------------------------------------------------------
?>

Reading Cookies in PHP

Cookies are placed in the $_COOKIE variable.

<?php

print_r($_COOKIE);

//----------------------------------------------------------
?>

Links




If you have found this site useful please consider linking to it @ http://www.poisedsolutions.com/cookies/

Social BookMarks
Google      Digg      Del.icio.us      Yahoo      Reddit      Facebook

Site Designed & Developed by Poised Solutions

If you wish to discuss hiring Poised Solutions for an information technology project please get in contact
or visit the main PoisedSolutions IT Consultancy Website.