ExposureRoom Home
  Log in Sign Up
Shiv's Website
Shiv Kumar
United States
Friends: 70
Focused on : 2
 
       
                                                             

What are Cookies?

Not Rated YetNot Rated YetNot Rated YetNot Rated YetNot Rated Yet0votes
January 05, 2008 02:40 PM  Views:43   Favorited:0 Comments:0
Filed Under:  Programming, Work
Tags:  Delphi, Internet, ISAPI
 

What are Cookies?

Cookies are a general mechanism which server side applications, such as CGI/ISAPI can use store information on the client side of the connection and later retrieve this same information. The addition of a simple, persistent, client side state significantly extends the capabilities of browser-based client/server applications.

Overview

A server, when returning an HTTP object (request) to a client, may also send a piece of state information, which the client will store. Included in that state object is a description of the range of URLs for which that state is valid. Any future HTTP requests made by the client that fall in that range will include a transmittal of the current value of the state object from the client back to the server. The state object is called a cookie, for no compelling reason.

This simple mechanism provides a powerful new tool, which enables a host of new types of applications to be written for browser-based environments. Shopping cart applications can now store information about the currently selected items. The server side of the connection controls the storage of information on the client. The information can be stored for a length of time or only during that current session. The current session terminates when the browser (application) on the client side of the connection is closed. The server side of the connection has access only to information that it stored. This forms a kind of protection mechanism in that, a server can not get information that another server had previously stored.

Specification

A cookie is introduced to the client by including a Set-Cookie header as part of an HTTP response. Typically this will be generated by a CGI, ISAPI, and ASP application. Syntax of the Set-Cookie HTTP Response Header

This is the format a web application would use to add cookie information to the HTTP headers.
Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure

NAME=VALUE
This string is a sequence of characters excluding semi-colon, comma and white space. If there is a need to place such data in the name or value, some encoding method such as URL style %XX encoding is recommended, though no encoding is defined or required. This is the only required attribute on the Set-Cookie header.
expires=DATE
The expires attribute specifies a date string that defines the valid life of that cookie. Once the expiration date has been reached, the cookie will no longer be stored or given out. The date string is formatted as:
Wdy, DD-Mon-YYYY HH:MM:SS GMT This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, with the variations that the only legal time zone is GMT and the separators between the elements of the date must be dashes.expires is an optional attribute. If not specified, the cookie will expire when the user's session ends.

Note: There is a bug in Netscape Navigator version 1.1 and earlier. Only cookies whose path attribute is set explicitly to "/" will be properly saved between sessions if they have an expires attribute.

domain=DOMAIN_NAME
When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is made with the Internet domain name of the host from which the URL will be fetched. If there is a tail match, then the cookie will go through path matching to see if it should be sent. "Tail matching" means that domain attribute is matched against the tail of the fully qualified domain name of the host. A domain attribute of "matlus.com" would match host names "delphi.matlus.com" as well as "delphi.isapi.matlus.com".

Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top-level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT". The default value of domain is the host name of the server, which generated the cookie response.

exclamation.gif Use 127.0.0.1 instead of localhost in your URLs when building and testing applications locally.

Using localhost will not persist cookies on the target (local) machine.

This issue has been one of the key factors related to issues programmers have when using cookies in the web applications/web sites.

path=PATH
The path attribute is used to specify the subset of URLs in a domain for which the cookie is valid. If a cookie has already passed domain matching, then the pathname component of the URL is compared with the path attribute, and if there is a match, the cookie is considered valid and is sent along with the URL request. The path "/foo" would match "/foobar" and "/foo/bar.html". The path "/" is the most general path. If the path is not specified, it as assumed to be the same path as the document being described by the header which contains the cookie.
secure
If a cookie is marked secure, it will only be transmitted if the communications channel with the host is a secure one. Currently this means that secure cookies will only be sent to HTTPS (HTTP over SSL) servers. If secure is not specified, a cookie is considered safe to be sent in the clear over unsecured channels.

Syntax of the Cookie HTTP Request Header
When requesting a URL from an HTTP server, the browser will match the URL against all cookies and if any of them match, a line containing the name/value pairs of all matching cookies will be included in the HTTP request (automatically). Here is the format of that line:
Cookie: NAME1=OPAQUE_STRING1; NAME2=OPAQUE_STRING2 ...

Additional Notes

  • Multiple Set-Cookie headers can be issued in a single server response.
  • Instances of the same path and name will overwrite each other, with the latest instance taking precedence. Instances of the same path but different names will add additional mappings.
  • Setting the path to a higher-level value does not override other more specific path mappings. If there are multiple matches for a given cookie name, but with separate paths, all the matching cookies will be sent.
  • The expires header lets the client know when it is safe to purge the mapping but the client is not required to do so. A client may also delete a cookie before its expiration date arrives if the number of cookies exceeds its internal limits.
  • When sending cookies to a server, all cookies with a more specific path mapping should be sent before cookies with less specific path mappings. For example, a cookie "name1=foo" with a path mapping of "/" should be sent after a cookie "name1=foo2" with a path mapping of "/bar" if they are both to be sent.
  • There are limitations on the number of cookies that a client can store at any one time. This is a specification of the minimum number of cookies that a client should be prepared to receive and store.
    1. 300 total cookies
    2. 4 kilobytes per cookie, where the name and the OPAQUE_STRING combine to form the 4 kbyte limit.
    3. 20 cookies per server or domain. (note that completely specified hosts and domains are treated as separate entities and have a 20 cookie limitation for each, not combined)
  • Servers should not expect clients to be able to exceed these limits. When the 300 cookie limit or the 20 cookie per server limit is exceeded, clients (browsers) should delete the least recently used cookie. When a cookie larger than 4 kb is encountered, the cookie should be trimmed to fit, but the name should remain intact as long as it is less than 4 kilobytes.
  • If a web application (CGI/ISAPI) script wishes to delete a cookie, it can do so by returning a cookie with the same name, and an expires time which is in the past. The path and name must match exactly in order for the expiring cookie to replace the valid cookie. This requirement makes it difficult for anyone but the originator of a cookie to delete a cookie.
  • When caching HTTP, as a proxy server might do, the Set-cookie response header should never be cached.
  • If a proxy server receives a response which contains a Set-cookie header, it should propagate the Set-cookie header to the client, regardless of whether the response was 304 (Not Modified) or 200 (OK).
  • Similarly, if a client request contains a Cookie: header, it should be forwarded through a proxy, even if the conditional If-modified-since request is being made.

    EXAMPLES

    Here are some sample exchanges, which are designed to illustrate the use of cookies.
    First Example transaction sequence:
    Client requests a document, and receives in the response:
    Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT
    When client requests a URL in path "/" on this server, it sends:
    Cookie: CUSTOMER=WILE_E_COYOTE
    Client requests a document, and receives in the response:
    Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
    When client requests a URL in path "/" on this server, it sends:
    Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
    Client receives:
    Set-Cookie: SHIPPING=FEDEX; path=/foo
    When client requests a URL in path "/" on this server, it sends:
    Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
    When client requests a URL in path "/foo" on this server, it sends:
    Cookie: CUSTOMER=SHIPPING=FEDEX;WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
    (Notice the order in which cookies are sent.)

    Second Example transaction sequence:
    Assume all mappings from above have been cleared.
    Client receives:
    Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
    When client requests a URL in path "/" on this server, it sends:
    Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001
    Client receives:
    Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo
    When client requests a URL in path "/ammo" on this server, it sends:
    Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001
    NOTE: There are two name/value pairs named "PART_NUMBER" due to the inheritance of the "/" mapping in addition to the "/ammo" mapping.

    So What Is A Cookie? A cookie is a small piece of information that is sent by a web server to be stored on a web browser, so that it can later be read back from that browser the next time this unique visitor returns to that web server. This becomes useful for having the browser remember specific information about this visitor like location of their last visit, time spent, or user preferences (like style sheets). The cookie is a text file that is saved in the browser's directory and is stored in RAM while the browser is running. Also, the cookie may be stored on the computer's hard drive once you log off from the web site or web server.

    What Are Cookies Used For? One use of cookies is for storing passwords and user ID's for specific web sites. The actual password may not be stored in the cookie per se, but a unique identifier for the user may be stored that can later be used to retrieve information from a database about the user. Also, they are used to store preferences of start pages. On sites with personalized viewing, your web browser will be requested to utilize a small amount of space on your computer's hard drive to store these preferences. That way, each time you log on to that web site, your browser will check to see if you have any pre-defined preferences (a cookie) for that unique server. If you do, the browser will send the cookie to the server along with your request for a web page. Microsoft and Netscape use cookies to create personal start pages on their web sites. Common uses for which companies utilize cookies, include:

    • on-line ordering systems
    • site personalization
    • web site tracking.
    Etc.

    Delphi and Cookies

    All this said, Delphi as is expected makes things a lot simpler. The TWebResponse object has a method called SetCookieFields. From the on-line help file:
    TWebResponse.SetCookieFields
    Adds a cookie header to the response message.
    procedure SetCookieField(Values: TStrings; const ADomain, APath: string;
       AExpires: TDateTime; ASecure: Boolean);
    
    Description
    Call SetCookieField to add a cookie header to the Cookies property. Each cookie header contains a set of name/value pairs that can be passed on by the client application. Use the Values parameter to specify the name/value pairs as strings of the form Name=Value. Use the ADomain and APath parameters to indicate which URLs the cookie should be sent to. Use the AExpires parameter to indicate when the cookie is no longer valid. Use the ASecure property to indicate whether the cookie should only be passed on by the client if a secure connection is used.

    The method name SetCookieFields, may be a bit confusing initially. It pertains to the fact that this method sets the Cookie fields of the HTTP header. While building CGI/ISAPI using Delphi, we don't really work directly with the HTTP header even though we do have full access to it if we need it.

    Another thing to understand is that each Name=Value pair is a cookie in and of itself. The method SetCookieFields, can set a whole list of cookies in one method call. But due to the nature of this, all cookies set will have the same path, domain, expiration date etc. This may not be what you want to do all the time. There will be times when you want to "expire" just one cookie or set just one cookie. The Method SetCookieFields can do that, but you need to explicitly create a TStrings derived object and free it.

    To overcome this confusion/limitation, I find myself frequently using a function called SetCookie that allows me to set just one cookie and frees me from having to create a TStrings derived object (normally a TStringList) and free it. Besides, it keeps the code clean and readable. Similarly, I create a function called GetCookie that returns the Value (part of the Name=Value pair) of the given Name.

    For further reading you might want to look at RFC 2109 that specifies Session State Management.

  • Comments have been Disabled for this post





    Menus

    Theme

    Privacy Policy  |  Terms Of Service  |  Contact Us  |  Support  |  Help/FAQs  |  News