[Back to Cookie Central]
Please visit our sponsors.



The Unofficial Cookie FAQ
Version 2.53

Contributed to Cookie Central by David Whalen


What's new in this release

Complete reorganization of the FAQ. Added 2 new Sections: General Questions/Miscellaneous and Advanced Topics. All new topics are indicated below.


A Note from the Author

(Version 2.5)
Well, well. A major update! Thanks for all your questions. I've tried to integrate them into the update as best as possible.

The FAQ has definitely gotten some attention lately! I have been interviewed 3 times, and the FAQ has been quoted a dozen or so times in articles on and off the Web. Not a bad little reception! I'm concerned that some people have chosen to quote the FAQ directly without my written permission. While I have no intention of getting in the way of spreading knowledge, I must insist that I be told when people intend to use my work. If you can't handle asking for permission, then don't use the FAQ in your works. If you're confused, feel free to read the Important Disclaimer and Copyright Information again.

Finally, thanks for all your kind letters and feedback. It helps remind me why I do the FAQ in the first place.

Thanks for stopping by!

-- DW

[Back to Top]



1. INTRODUCTION

Cookies are a very useful tool in maintaining state variables on the Web. Since HTTP is a "stateless" (non-persistent) protocol, it is impossible to differentiate between visits to a web site, unless the server can somehow "mark" a visitor. This is done by storing a piece of information in the visitor's browser.

This is accomplished with cookies. Cookies can store database information, custom page settings, or just about anything that would make a site individual and customizable. An analogy I like to use is that cookies are very much like a laundry "claim-check" of sorts. You drop something off, and get a ticket. When you return with the ticket, you get that same something back.

1.1 What is a Cookie?

A cookie is simply an HTTP header that consists of a text-only string that gets entered into the memory of a browser. This string contains the domain, path, lifetime, and value of a variable that a website sets. If the lifetime of this variable is longer than the time the user spends at that site, then this string is saved to file for future reference.

1.2 Where did the term cookies come from?

According to an article written by Paul Bonner for Builder.Com on 11/18/1997:

"Lou Montulli, currently the protocols manager in Netscape's client product division, wrote the cookies specification for Navigator 1.0, the first browser to use the technology. Montulli says there's nothing particularly amusing about the origin of the name: 'A cookie is a well-known computer science term that is used when describing an opaque piece of data held by an intermediary. The term fits the usage precisely; it's just not a well-known term outside of computer science circles.'"

1.3 Why do sites use Cookies?

There are many reasons a given site would wish to use cookies. These range from the ability to personalize information (like on My Yahoo or Excite), or to help with on-line sales/services (like on Amazon Books or Microsoft), or simply for the purposes of tracking popular links or demographics (like DoubleClick). Cookies also provide programmers with a quick and convenient means of keeping site content fresh and relevant to the user's interests. The newest servers use cookies to help with back-end interaction as well, which can improve the utility of a site by being able to securely store any personal data that the user has shared with a site.

1.4 Where Can I Get More Information?

Cookie Central is dedicated to answering questions about cookies. If you can't find your answers there, one may not exist.

The World Wide Web Consortium has an excellent FAQ to answer the majority of Internet and Web-related questions. You can read their topic: "Do 'Cookies' Pose any Security Risks?"

In addition, there are an abundance of resources on the Internet that can help you find answers to your cookie questions. Conveniently, Yahoo has a great listing of them. I encourage you to stop by and check the list out!

If you like having an actual paper book by your side, I strongly encourage Simon St. Laurent's cookies, published by Computing McGraw Hill. You can find it on Amazon.com, or try your local bookstore!

[Back to Top]



2. GENERAL QUESTIONS/MISCELLANEOUS

2.1 Introduction

This section is devoted to general questions on cookies and their usage.

2.2 Can I delete cookies?

Yes. Whether you use Netscape or Microsoft Internet Explorer (MSIE), your cookies are saved to a simple text file that you can delete as you please.

In order to do this properly, remember to close your browser first. This is because all your cookies are held in memory until you close your browser. So, if you delete the file with your browser open, it will make a new file when you close it, and your cookies will be back.

Remember that deleting your cookie file entirely will cause you to "start from scratch" with every web site you usually visit. So, it may be preferable to open the cookies.txt file (in the case of Netscape) and remove only the entries you don't like, or go to the cookies folder (in the case of MSIE) and delete the files from servers you don't want.

2.3 How do I set my browser to reject cookies?

Both Netscape and Microsoft Internet Explorer (MSIE) allow some level of cookie verification. Netscape 3.0 and MSIE 3.0 allow you only to "alert before accepting cookies." This is done through the Options/Network Preferences/Protocols menu (for Netscape) or the Internet Options/Advanced menu (for MSIE). This means you can read each cookie as it comes in, and hit "OK" to allow it, or "Cancel" to reject it.

Netscape 4.0 and MSIE 4.0 go one better. They have menu options that allow you to accept all, some, or none of your incoming cookies. In addition, the "warn before accepting" feature is still present in both, if you want to screen your incoming cookies.

In Netscape 4.0, go to the Edit/Preferences/Advanced menu. You will see all of the above choices. In MSIE 4.0, go to the View/Internet Options/Advanced menu. There you can accept all, warn before accepting, or reject all.

MSIE 5.0 has a lot of menu and dialog changes, but you can still disable cookies. Go to the Tools/Internet Options/Security menu. In there, you can choose the security level for 4 different browsing conditions: Internet Sites, Local Sites, "Trusted" Sites, and Restricted Sites. If you select "Internet," and click on Custom Level, you'll get a dialog box where you can accept all, warn before accepting, or reject all cookies.

Once a cookie is rejected, it is thrown out and not saved to memory or disk. Don't forget, though, that servers will keep looking for the cookie even if you have discarded it and may try to replace it as you surf around.

This fact is almost comical in nature. Essentially, without a cookie to tell the server who you are, it can't remember not to send you any cookies!

2.4 Are Cookies Dangerous to My Computer?

NO. A cookie is a simple piece of text. It is not a program, or a plug-in. It cannot be used as a virus, and it cannot access your hard drive. Your browser (not a programmer) can save cookie values to your hard disk if it needs to, but that is the limit of the effect on your system.

2.5 Will cookies fill up my hard drive?

Both Netscape and Microsoft have measures in place that limit the number of cookies that will be saved on your hard drive at one time.

Netscape limits your total cookie count to 300. If you exceed this, the browser will discard your least-used cookies to make room for the new ones.

Microsoft saves cookies into the "Temporary Internet Files" folder, a system folder that you can set the maximum size of (the default is 2% of your hard drive).

In any event, remember that the average size of a cookie ranges from 50-150 bytes. You would need about 20 million cookies to fill up a 2GB drive. This is incredibly unlikely.

2.6 Are Cookies a Threat to My Privacy?

As with everything else about the Internet, you are only as anonymous as you want to be. The sad truth is that revealing any kind of personal information opens the door for that information to be spread. The very nature of Web servers allows for the tracking of your surfing habits alone, and other information about you can be gathered with time.

While cookies themselves are not gathering that data, they are, unfortunately, used as a tracking device to help the people who are gathering that information. As information is gathered about you, it is associated with the value they keep in your cookie.

To reiterate, A COOKIE ALONE CANNOT READ YOUR HARD DRIVE TO FIND OUT WHO YOU ARE, WHAT YOUR INCOME IS, OR WHERE YOU LIVE. The only way that information could end up in a cookie is if YOU provide it to a site and that site saves it to a cookie.

The never-ending ethical debate associated with these facts shall be left to other forums. However, it is wise to consider carefully the information you collect and share over the Internet.

2.7 Sites are telling me I need to turn on cookies, but they are on. What's wrong?

There are three likely possibilities for problems like this. Firstly, the site you are visiting may be detecting cookies improperly. As a result, it may appear to the site that you are rejecting cookies when in fact you are not.

Another possibility is that you may be running software that interferes with cookie usage. There are many filtering and blocking software packages available for Internet users these days, and many of them also filter cookies. If you are running software like this, then your computer may not receive or send cookies. This will cause sites you visit to assume you are not accepting cookies.

Finally, your machine may be behind a firewall or proxy server that prevents cookie transmission. This is most likely in a corporate environment. So, regardless of how your browser is set, cookies won't be sent or received by your browser. Since the cookies aren't making it through to your browser, the Web Site will assume you personally aren't accepting them.

2.8 I deleted my cookies, and I can't log-on to my favorite site anymore. What can I do?

Many sites use a cookie to keep track of your settings on their servers, and to help you log in to their site. If you lose your cookie, that site cannot recall your settings for you to use.

If this happens to you, the best thing you can do is contact that site's webmaster or customer service department.

2.9 How did I get a cookie from doubleclick.net? I've never been there!

From section 3.3, we see that a server cannot set a cookie for a domain that it isn't a member of. However, almost every Web user has gotten a cookie from "ad.doubleclick.net" at one time or another, without ever visiting there. DoubleClick and other advertisers have employed a clever solution that enables them to track users and serve media content without violating this rule.

Most sites on the Internet do not keep their advertisements locally. Rather, they subscribe to a media service that places those ads for them. This is accomplished via a simple HTML call to the media service. When a page is requested, it is assembled through many HTTP requests by the browser. First, there is a request for the HTML itself. Then, everything the HTML needs is requested, including images, sounds, and plugins.

The call to the media service is an HTTP request for an image. Once the request is made to the media service, it can return more than just an ad. It can also return a cookie. Or, if is has given the user a cookie previously, it can read that first, and check to see what ad to send. The net result is that the user gets a cookie from the media service without ever having visited it.

This usage of cookies is the most controversial, and has led to the polarized opinions on cookies, privacy, and the Internet.

2.10 I looked at my Internet Explorer cookies, and they had my username on them! Can servers see my username?

Because Windows systems allow more than one user to login and use programs, Microsoft had to come up with a way to keep each user's cookies separate on a given machine. This can be common in workplaces, where a single machine is shared by many employees.

This is accomplished by appending the username to the cookie file name. This way, both Jane Doe and Joe Smith can get cookies from coolsite.com and they don't get over-written. Also, this stop's Jane from using Joe's cookies while she's surfing, since the browser will only use her cookies when she is logged in. That is, the cookie file:

jdoe@coolsite.txt

Contains Jane Doe's cookie for coolsite.com. If anyone else logs-in, then this cookie is not used.

This is the only reason that the username is part of the cookie file name. The username does not get sent to the server with the cookie data.

[Back to Top]



3. COOKIE FUNDAMENTALS

3.1 Introduction

Whether you're a programmer or just a web user looking for answers, a big part of understanding cookies is to go into the gory details. This section does just that.

3.2 How does a cookie really work?

Understanding how cookies really work requires an understanding of how HTTP works. Cookies transport from Server to Client and back as an HTTP header. The specifications for this header are explicitly laid out in RFC 2109.

When a cookie is sent from the server to the browser, an additional line is added to the HTTP headers (example):

Content-type: text/html
Set-Cookie: foo=bar; path=/; expires Mon, 09-Dec-2002 13:46:00 GMT

This header entry would result in a cookie named foo. The value of foo is bar. In addition, this cookie has a path of /, meaning that it is valid for the entire site, and it has an expiration date of Dec 9, 2002 at 1:46pm Greenwich Mean Time (or Universal Time). Provided the browser can understand this header, the cookie will be set.

When a cookie is sent from the browser to the server, the cookie header is changed slightly:


Content-type: text/html
Cookie: foo=bar

Here, the server is made aware of a cookie called foo, whose value is bar.

3.3 Breakdown of Cookie Parameters

As we have just seen, a cookie contains more than simply a name and a value. In fact, a cookie has 6 parameters that can be passed to it:

  • The name of the cookie,
  • The value of the cookie,
  • The expiration date of the cookie,
  • The path the cookie is valid for,
  • The domain the cookie is valid for,
  • The need for a secure connection to exist to use the cookie.

Two of these are mandatory (its name and its value). The other four can be set manually or automatically. Each parameter is separated by a semicolon when set explicitly. Here is a detailed description of each.

Name, Value

The name of a cookie and its value are set simply by pairing them together:


... foo=bar ...
The value of a cookie can also be null, for the purpose of clearing the cookie value:

... foo= ...

Expires

The expires parameter lets you determine the lifetime of the cookie.


... expires=Mon, 01-Jan-2001 00:00:00 GMT ...

If Expires is not set explicitly, then it defaults to end-of-session. The length of a session can vary depending on browsers and servers, but generally a session is the length of time that the browser is open for (even if the user is no longer at that site).

Path

The path parameter is potentially the most useful of the 4 optional cookie settings. It sets the URL path the cookie is valid within. Pages outside of that path cannot read or use the cookie.

... path=/promo ...

If Path is not set explicitly, then it defaults to the URL path of the document creating the cookie.

Netscape has identified a bug for VERY old versions of Navigator where the path must be specified if an expiration is specified. Furthermore, this path must be set to "/". For more information, browse Netscape's Cookie Spec at:
http://www.netscape.com/newsref/std/cookie_spec.html

Domain

The domain parameter takes the flexibility of the path parameter one step further. If a site uses multiple servers within a domain the it is important to make the cookie accessible to pages on any of these servers.

... domain=www.myserver.com ...

Cookies can be assigned to individual machines, or to an entire Internet domain. The only restrictions on this value is that it must contain at least two dots (.myserver.com, not myserver.com) for the normal top-level domains, or three dots for the "extended" domains (.myserver.ny.us, not myserver.ny.us)

IMPORTANT: The server issuing the cookie must be a member of the domain that it tries to set in the cookie. That is, a server called www.myserver.com cannot set a cookie for the domain www.yourserver.com. The security implications should be obvious.

If Domain is not set explicitly, then it defaults to the full domain of the document creating the cookie.

Secure

The secure parameter is a flag indicating that a cookie should only be used under a secure server condition, such as SSL. Since most sites do not require secure connections, this defaults to FALSE.

3.4 How do cookies end up on my hard drive?

After a cookie is transmitted through an HTTP header, it is stored in the memory of your browser. This way the information is quickly and readily available without re-transmission. As we have seen, however, it is possible for the lifetime of a cookie to greatly exceed the amount of time the browser will be open.

In such cases, the browser must have a way of saving the cookie when you are not browsing, or when your computer is shut off. The only way the browser can do this is to save the cookies in memory to the hard drive. This way, when you start your browser a few days later, you still have the cookies you had previously.

The browser is constantly performing maintenance on its cookies. Every time you open your browser, your cookies are read in from disk, and every time you close your browser, your cookies are re-saved to disk. As a cookie expires, it is discarded from memory and it is no longer saved to the hard drive.

3.5 What are all those entries in my cookies.txt file?

The layout of Netscape's cookies.txt file is such that each line contains one name-value pair. An example cookies.txt file may have an entry that looks like this:

.netscape.com     TRUE   /  FALSE  946684799   NETSCAPE_ID  100103

Each line represents a single piece of stored information. A tab is inserted between each of the fields.

From left-to-right, here is what each field represents:

domain - The domain that created AND that can read the variable.
flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
path - The path within the domain that the variable is valid for.
secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
name - The name of the variable.
value - The value of the variable.

3.6 Where does MSIE keep its cookies?

Microsoft keeps its cookies in different locations, depending on the version you are using. If you are using Explorer 3.x, you will find your cookies in the folder c:\windows\cookies.

If you use Explorer 4.x, however, you will notice that Cookies are instead located in c:\windows\Temporary Internet Files. Although the location is different, the format is the same. Each individual domain's cookies are stored in their own file, along with the username that accessed the site. For example, if I went to Yahoo in IE4, I would get a cookie that is stored in the file Cookie:dwhalen@yahoo.com.

Note that the username is not sent with the cookie. See Section 2.10 for more information.

3.7 Are cookies Year 2000 Compliant?

There is no date-specific restriction on the HTTP header used to transmit cookies. In fact, the only determining factor in whether a cookie will be accepted is the programming of the client receiving the cookie.

The major browsers do not have an issue with this. Cookies with expiration dates set with 2-digit or 4-digit years are understood properly. Naturally, it's always advisable to use 4-digit years when setting cookies.

[Back to Top]



4. COOKIE CREATION

4.1 Introduction

Creating a cookie generally involves duplicating the HTTP cookie header in some fashion so that the browser will store the name-value pair in memory. Some languages expect an exact HTTP header to be sent, while others will use built-in functions to help you speed the process along.

Cookies can be set from the browser-side or from the server-side. The determining factor will be the language you use to create the cookie. Once the cookie is created, it should flow easily from server to client and back via the HTTP headers.

4.2 Creating cookies with JavaScript

JavaScript supplies a built-in object called document.cookie to handle cookie interaction. This object will store all the valid cookies for the given page the script is running on.

When you insert a value into document.cookie, a cookie will be created. The syntax is identical to that of the HTTP header:


<SCRIPT LANGUAGE="JavaScript">
document.cookie="foo=bar; path=/; expires=Mon, 01-Jan-2001 00:00:00 GMT";
</SCRIPT>

Bill Dortch at hIdaho Design (bdortch@hidaho.com) has the most comprehensive set of functions for cookie management from the Client. One such function is SetCookie (all of his functions can be found at http://www.hidaho.com/cookies/cookie.txt):

<SCRIPT LANGUAGE="JavaScript">
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
</SCRIPT>

This function requires that a name and a value are passed, with all other parameters optional. A sample use of this function could be the following:

<SCRIPT LANGUAGE="JavaScript">
setCookie("foo", "bar", "Mon, 01-Jan-2001 00:00:00 GMT", "/");
</SCRIPT>

The SetCookie function is more versatile if you wish to make many cookies, or if you want to set the parameters on-the-fly.

4.3 Creating cookies with PERL

As with most HTTP-related processes in PERL, cookies are set by writing an actual header to the response for an HTTP request. Most PERL programmers are used to writing headers like the following:


Content-type: text/html

This is a MIME header that explains that the content following is text-based HTML code. Similarly, we could write the cookie header directly:

Content-type: text/html
Set-Cookie: foo=bar; path=/; expires=Mon, 01-Jan-2001 00:00:00 GMT

Here, an HTML page would follow after a cookie has been set.

Another very popular HTTP header used in PERL is Location. Be aware that Location is best placed as the last header in a group:


Content-type: text/html
Set-Cookie: foo=bar; path=/; expires=Mon, 01-Jan-2001 00:00:00 GMT
Location: http://www.mysever.com

4.4 Creating cookies with LiveWire

To make a cookie with LiveWire, simply use the client object like so:


client.foo = bar;
client.expiration(expire);

Where expire is the number of milliseconds that you wish the cookie to live for.

Note: When transmitted via HTTP, any methods of the client object will have the prefix NETSCAPE_LIVEWIRE appended to them to help LiveWire restore these values into the client object in the future.

In this example, the cookie that is actually transmitted is named NETSCAPE_LIVEWIRE.foo

4.5 Creating cookies with Active Server Pages

Setting cookies requires usage of the Response.Cookies Object in ASP. This Object contains parameters equivalent to each possible parameter in the normal HTTP header:


Response.Cookies("foo") = "bar"
Response.Cookies("foo").Expires = "January 1, 2001"
Response.Cookies("foo").Domain = "myserver.com"
Response.Cookies("foo").Path = "/"
Response.Cookies("foo").Secure = FALSE

4.6 Creating cookies with VBScript

Creating a cookie in VBScript is almost identical to that of JavaScript:

<SCRIPT LANGUAGE="VBScript">
document.cookie="foo=bar; path=/; expires Mon, 01-Jan-2001 00:00:00 GMT"
</SCRIPT>

The differences would come about in creating a subroutine to do this for you quickly:

<SCRIPT LANGUAGE="VBScript">
Sub SetCookie (name, value, expires, path, domain, secure)
    setStr = name & "=" & value
    If (expires <> "") Then setStr = setStr & "; expires=" & expires
    If (path <> "") Then setStr = setStr & "; path=" & path
    If (domain <> "") Then setStr = setStr & "; domain=" & domain
    If (secure <> "") Then setStr = setStr & "; secure"
    document.cookie = setStr
End Sub
</SCRIPT>

Note two main differences, both of which affect the call to this subroutine. Firstly, the value is not explicitly URL-encoded ("escaped") for you. This must be done by hand. Secondly, all parameters must be explicitly listed in the call or the call will fail:

<SCRIPT LANGUAGE="VBScript">
SetCookie "foo","bar","Mon, 01-Jan-2001 00:00:00 GMT","/","myserver.com",""
</SCRIPT>

4.7 Limits on Cookie Creation

There are limits on the contents of both the cookie string and the cookie file. These limits are partially imposed by HTTP and partially by arbitrary choice. They are as follows:

  • You CANNOT set Cookies for domains other than those that the document resides in. That is, a page on www.myserver.com can set a Cookie for myserver.com and www.myserver.com, but NOT www.yourserver.com.
  • The cookie HTTP header must be no more than 4K in size.
  • For Netscape, domains can only set a maximum of 20 cookies each on a specific Client. This does not mean the true internet domain, but only the domain specified via document.cookie. If you have 20 cookies for www.myserver.com, and another 20 cookies for .myserver.com, this is allowed. For each cookie past 20, the least recently used cookie is deleted.
  • Also for Netscape, the cookie area may only hold a maximum of 300 total cookies from all sources. For each cookie past 300, the least recently used cookie is deleted.

Note that this applies to cookies while they are in memory or stored in the cookies.txt file.

[Back to Top]



5. COOKIE RETRIEVAL

5.1 Introduction

For the most part, retrieving cookies does not require reading the HTTP Cookie: header. Most languages read this header for you and make it accessible through a variable or object.

Cookies can be read on the browser side or the server side. Again, the determining factor is the language used.

5.2 Retrieving cookies with JavaScript

To retrieve cookies with JavaScript, use document.cookie again. Typically, document.cookie has a string like so:


foo=bar;this=that;somename=somevalue;.....

This string contains every name-value pair valid for this document, separated by semicolons. This can make searching for your needed value a bit of a pain. The getCookie() function does make this simpler:

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

The results are directed into variables in your routine:

myVar = GetCookie("foo");

Here, myVar would equal bar.

5.3 Retrieving cookies with PERL

On platforms that support the environment variable $ENV{'HTTP_COOKIE'} (such as Solaris), cookies can be read into PERL with that environment variable.

As with JavaScript, the returned value is valid name-value pairs for this document, separated by semicolons. Again, it is simpler to write a parsing routine for this header:


@nvpairs=split(/; /, $ENV{'HTTP_COOKIE'});

foreach $pair (@nvpairs) {
        ($name, $value) = split(/=/, $pair);
        $cookie{$name} = $value;
}

A call would be like:

$myVar = $cookie{'foo'};

Here, myVar would equal bar.

5.4 Retrieving cookies with LiveWire

To retrieve cookies into LiveWire, again use the client object. Any cookies headed with the prefix NETSCAPE_LIVEWIRE will be made into methods of the client object. Thus, any methods on the client object that have not expired from the previous session will still be available.


myVar = client.foo;

Here, myVar would equal bar.

5.5 Retrieving cookies with Active Server Pages

To retrieve cookies into ASP, use the Request.Cookies object. All the cookies valid for this document are pre-parsed into this object for you for quick and easy access.

So, all you need to do to access a value is simply write:


myVar = Request.Cookies("foo")

Again, myVar equals bar.

5.6 Retrieving cookies with VB Script

To retrieve cookies into VB Script, use the Document.Cookies object. All the cookies valid for this document are in a semicolon-delimited string, like with JavaScript.

To parse the string, use a function like so (courtesy of microsoft.com web site):

<SCRIPT LANGUAGE="VBScript">
Function GetCookie(strVariableName)
  intNameLength = Len(strVariableName)
  intLocation = Instr(Document.Cookie, strVariableName)
  If intLocation = 0 Then
    GetCookie = ""
  Else
    strTemp = Right(Document.Cookie, Len(Document.Cookie) - intLocation + 1)
    If Mid(strTemp, intNameLength + 2, 1) <> "=" Then
      GetCookie = ""
    Else
      intNextSemicolon = Instr(strTemp, ";")
      If intNextSemicolon = 0 Then
        intNextSemicolon = Len(strTemp) + 1
      End If
      If intNextSemicolon = (intNameLength + 2) Then
        GetCookie = ""
      Else
        intValueLength = intNextSemicolon - intNameLength - 2
        GetCookie = Mid(strTemp, intNameLength + 2, intValueLength)
      End If
    End If
  End if
End Function
</SCRIPT>

Calling this Function like so:

myVar = GetCookie("foo")

Yields the value bar.

5.7 Limits on Cookie Retrieval

The main limit on retrieving a cookie is that you can only retrieve cookies that are valid for the document your script resides in. That is, a script on www.myserver.com cannot read cookies from www.yourserver.com. This is mainly governed on the browser side, as browsers know the URL that they are accessing, and only transmit cookies for that server across the connection.

[Back to Top]



6. ADVANCED TOPICS

6.1 Introduction

This section covers topics beyond the normal creation and retrieval of cookies.

6.2 Clearing a Cookie Value

When programming a Web site, there are many reasons that you may need to erase a cookie you have created. Often it is because the cookie is no longer needed, or the scheme of your cookie has been altered, and requires resetting.

The two main steps to clearing a cookie you have created are:

  1. Set the cookie's value to null.
  2. Set the cookie's expiration date to some time in the past.
For example, if I wish to clear the "foo" cookie forever, I should set it with the HTTP header:

Content-type: text/html
Set-Cookie: foo=; path=/; expires Thu, 01-Jan-1970 00:00:00 GMT

The reason you must do both is that simply setting the expiration to a past time will not change it's value until the browser is closed. That is, all cookie names, values, expirations, etc are resolved once the browser program has been closed. Setting the cookie to null allows you to properly test for the cookie until that resolution.

6.3 Detecting if cookies are accepted

To properly detect if a cookie is being accepted via the server, the cookie needs to be set on one HTTP request and read back in another. This cannot be accomplished within 1 request. When using PERL or ASP, try to funnel your visitors through a common page where you can set a test cookie. Then, when the time comes to detect, check for that cookie.

If you use client-side languages to set a cookie, you can set and read on the same page. Cookies set by JavaScript or VBScript reside in the browser's memory already, so you will know if they have been accepted right away. Check by setting a test value, and then try to read that value back out of the cookie. If the value still exists, the cookie was accepted.

6.4 The ASP Session Object

Microsoft's Active Server Pages have a built-in object for the purpose of using session-related variables. The approach is to tie all session values to a single cookie, rather than assign a cookie to each individual value. This can be a big advantage for programmers because keeping track of cookies can become tiresome.

Internet Information Server (IIS) 3.0 and 4.0 both set a single cookie for every visitor, called ASPSESSIONID. The value set within this cookie points back to a server database which holds the session values set by the programmer. This is all built-in to IIS and doesn't require any additional setup to use. Simply use the Session object as described in the ASP documentation.

6.5 The LiveWire Client Object

Netscape's LiveWire also has a built-in object for using session-related variables. Unlike Microsoft's IIS, LiveWire allows you to select how you wish to involve cookies with this object.

If you use LiveWire's "client-cookie" state maintenance for a site, then you should refer to the right sections in parts 4 and 5, above. This will give a clearer picture on how to use this properly.

If you use LiveWire's "server-cookie" state maintenance for a site, then the behavior is very similar to that of IIS. A single cookie is sent to the visitor that points to a database on the server where all the session variables are maintained.

[Back to Top]

About the Author

David Whalen is a Software Engineer. David writes Web-based applications in ASP, PERL, Java, and JavaScript. He has worked in the Web industry for 4 years. David is a Microsoft Certified Professional. In addition, he was an inaugural Netscape DevEdge Champion, where he provided third-party support to developers in JavaScript and Netscape's LiveWire.

David is 29 years old. He holds a Masters Degree in Astrophysics from the University of Wyoming. His personal interests include traveling, photography, gaming, animation, and sporting. When not programming, he can be found either playing Quake 2 or out on the golf course.

Copyright ©1999 David Whalen. This document is provided "as is" without any guarantees or warranty. Although the author has attempted to find and correct any errors or mistakes he, and everyone who contributed to it, are not responsible for any damage or losses of any kind caused by the use or misuse of information in this FAQ. The author is under no obligation to provide service, corrections, or upgrades to this FAQ.

The following is legal information and refers to all the information in this document. This information pertains to all use of the FAQ worldwide. All specific names included in the package are registered trademarks and are hereby acknowledged. Any other trademarks not mentioned in the FAQ are still hypothetically acknowledged.

  • No portion of the document may be separated and distributed separately without the written permission of the author, David Whalen.
  • The document can not be included in any publication, such as, but not limited to: magazines, books, newspapers or newsletters, without the written permission of the author.
  • The document can not be included in any software compilation using media such as, but not limited to: CD-ROM, tape backup, optical disks, hard disks or memory cards, without the written permission of the author.
  • The document can not be recompiled, modified or not, and distributed without the written permission of the author.
  • Visitors are encouraged to send submissions and error fixes to the author, but the author is in no way obliged to utilize these enhancements or fixes.
  • In the event of ambiguity or omission within this notice, all rights and ownership are retained by the author.
  • Last Modified: 05/10/1999

    [Back to Top]