HTTP State Management with Cookies - Implementation
(Page 3 of 5 )
From a web development point of view, there are various methods by which cookies can be implemented. Broadly speaking, they can be implemented in a straightforward manner through common web development languages including JavaScript, PHP and ASP, all of which have functions for creating cookies and specifying their contents. Plain HTML cannot be used to implement cookies.
Cookies and JavaScript
Cookies can be manipulated in JavaScript using the document.cookie property. This property makes it relatively easy to create reusable functions for setting and retrieving them. A simple function to set a cookie containing just the required name=value pair might look something like this:
function makecookie( name, value ) {
var my_cookie = name + "=" + escape( value );
document.cookie = my_cookie;
}
A slightly more complex function is needed to retrieve the cookie's information, since it is necessary to parse all the document's cookies for the one we want. To do this, the document.cookie property can be treated as a string. Either the search or match method will work, e.g.:
function readcookie( name ) {
var Name = document.cookie.match ( '(^|;) ?' + name + '=([^;]*)(;|$)' );
if ( name )
return ( unescape ( name[2] ) );
else
return null;
}
More complex cookies can be constructed by including additional parameters in the function declaration. In this example three parameters are used to specify the expiry date:
function makecookie ( name, value, x-y, x-m, x-d) {
var x_date = new Date ( x-y, x-m, x-d );
var my_cookie = name + "=" + escape( value ) + "; expires=" + x_date.toGMTString();
document.cookie = my_cookie;
}
The toGMTString method converts the supplied year, month and day to a format suitable for defining cookie expiration dates. You can use the expiry parameter to delete the cookie, by invoking the function and supplying the current date and time for expiry.
Next: Cookies and PHP >>
More Server Administration Articles
More By Bruce Coker