Web Design

NOTE: This is a collection of information and links collected over the years that might provide useful information. A Safer Company LLC does not guarantee, endorse or approve any of these links or their scripts. Use these links to other websites at your own risk.

Cookies

A cookie is a small text file that is stored in your computer. It contains the following data:

  1. A name-value pair containing the actual data -the name of the cookie is for your benefit, you will search for the cookie name when reading the cookie information
  2. An expiry date after which it is no longer valid - If you don't specify the expiry date the cookie is trashed when you close the browser. This expiry date should be in UTC (Greenwich) time.
  3. The domain and path of the server it should be sent
    • Not specified - uses the domain of the page that sets the cookie
    • Usually the path is set to /, which means the cookie is valid throughout the entire domain

As soon as you request a page from a server to which a cookie should be sent, the cookie is added to the HTTP header. Server side programs can then read out the information and decide that you have the right to view the page you requested or that you want your links to be yellow on a green background.

document.cookie

Cookies can be created, read and erased by JavaScript using the property document.cookie and should be accessed using the name-value pairs.Cookies use a very strict syntax.

Example Set Cookie:

  • Set a cookie for this domain with a name-value pair 'ppkcookie1=test1cookie' that expires in seven days:
document.cookie = 'ppkcookie1=test1cookie; expires=Thu, 2 Aug 2012 20:47:11 UTC; path=/'  

Multiple cookies can be set.

document.cookie = 'ppkcookie2=test2cookie; expires=Fri, 3 Aug 2012 20:47:11 UTC; path=/'  

The second cookie is added to document.cookie, so it is read:

ppkcookie1=test1cookie; ppkcookie2=test2cookie  

Reset a Cookie

document.cookie = 'ppkcookie2=test3cookie; expires=Fri, 3 Aug 2012 20:47:11      UTC; path=/'  

The ppkcookie2 was given the value test3cookie.

ppkcookie1=testcookie; ppkcookie2=test3cookie  

Reading Cookies

To read a cookie you have to treat document.cookie as a string and search for certain characters (semicolons, for instance) and for the cookie name.

Finally, to remove a cookie, set it with an expiry date before today. The browser sees that the cookie has expired and removes it.

document.cookie = 'ppkcookie2=yet another test; expires=Fri, 27 Jul 2012 02:47:11 UTC; path=/'

Example

Set two cookies, ppkcookie1 and ppkcookie2. Fill in the desired value in the text box.

The value of the cookie should be

Create cookie 1

Read cookie 1

Erase cookie 1.

Create cookie 2

Read cookie 2

Erase cookie 2.

For comparision, read out document.cookie.

I set the cookies to remain active for seven days. If you return to this page within that time, you'll get an alert that the cookie(s) is/are still active. Try it by setting a cookie, then reloading this page.

The scripts

These are the three scripts you need.

function createCookie(name,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 = name+"="+value+expires+"; path=/";  }    function readCookie(name) {  	var nameEQ = name + "=";  	var ca = document.cookie.split(';');  	for(var i=0;i < ca.length;i++) {  		var c = ca[i];  		while (c.charAt(0)==' ') c = c.substring(1,c.length);  		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);  	}  	return null;  }    function eraseCookie(name) {  	createCookie(name,"",-1);  }  
 

Explanation

<script type="text/javascript">
<!--
function saveIt(name) {
      var x = document.forms['cookieform'].cookievalue.value;
      if (!x)
      alert('Please fill in a value in the input box.');
      else {
      Cookies.create(name,x,7);
      alert('Cookie created');
      }
      }
function readIt(name) {
      alert('The value of the cookie is ' + Cookies[name]);
      }
function eraseIt(name) {
      Cookies.erase(name);
      alert('Cookie erased');
      }
function init() {
      for (var i=1;i<3;i++) {
      var x = Cookies['ppkcookie' + i];
      if (x) alert('Cookie ppkcookie' + i + '\nthat you set on a previous visit,      is still active.\nIts value is ' + x);
      }
      }
      // -->
</script>
 

createCookie

When calling createCookie() you have to give it three bits of information: the name and value of the cookie and the number of days it is to remain active. In this case the name-value pair should become ppkcookie=testcookie and it should be active for 7 days.

createCookie('ppkcookie','testcookie',7)

If you set the number of days to 0 the cookie is trashed when the user closes the browser. If you set the days to a negative number the cookie is trashed immediately.

The function receives the arguments and starts doing its job.

function createCookie(name,value,days) {

First of all see if there is a days value. If there isn't we don't need to do the time calculation.

if (days) {

If there is, create a new Date object containing the current date.

var date = new Date();

Now get the current Time (in milliseconds) and add the required number of days (in milliseconds). Set the Time of the date to this new value, so that it now contains the date in milliseconds that the cookie should expire.

date.setTime(date.getTime()+(days*24*60*60*1000));

Set the variable expires to this date in the UTC/GMT format required by cookies.

var expires = "; expires="+date.toGMTString(); }

If 0 is passed to the function, expires is not set and the cookie expires when the user closes his browser..

else var expires = "";

Finally write the new cookie into document.cookie in the correct syntax.

document.cookie = name+"="+value+expires+"; path=/"; }

Cookie created.

readCookie

To read out a cookie, call this function and pass the name of the cookie. Put the name in a variable. First check if this variable has a value (if the cookie does not exist the variable becomes null, which might upset the rest of your function), then do whatever is necessary.

var x = readCookie('ppkcookie1') if (x) { [do something with x] }

The function receives the argument and starts.

function readCookie(name) {

We're going to search for the name of the cookie, followed by an =. So create this new string and put it in nameEQ:

var nameEQ = name + "=";

Then split document.cookie on semicolons. ca becomes an array containing all cookies that are set for this domain and path.

var ca = document.cookie.split(';');

Then we go through the array (so through all cookies):

for(var i=0;i < ca.length;i++) {

Set c to the cookie to be checked.

var c = ca[i];

If the first character is a space, remove it by using the substring() method. Continue doing this until the first character is not a space.

while (c.charAt(0)==' ') c = c.substring(1,c.length);

Now string c begins with the name of the current cookie. If this is the name of the desired cookie

if (c.indexOf(nameEQ) == 0)

we've found what we were looking for. We now only need to return the value of the cookie, which is the part of c that comes after nameEQ. By returning this value we also end the function: mission accomplished.

if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); }

If, after having gone through all cookies, we haven't found the name we're looking for, the cookie is not present. We return null.

return null; }

Cookie read.

eraseCookie

Erasing is extremely simple.

eraseCookie('ppkcookie')

Pass the name of the cookie to be erased

function eraseCookie(name) {

and call createCookie() to set the cookie with an expiry date of one day ago.

createCookie(name,"",-1); }

The browser, seeing that the expiry date has passed, immediately removes the cookie.

 

top of page

It is all about:
Content and Navigation...

Web Site by: A Safer Company LLC

Office Use ONLY