The code above creates a cookie that expires at 2.45pm on 31/7/2009 and stores the string "Hello". The cookie attributes are explained below.
The name attribute
In this case the name of the cookie is mycookie and is followed by = then the string to store. However cookies don't allow commas, semicolons or whitespace within the string.
Since you're quite likely to use these characters in a cookie then you should use the JavaScript escape() function when creating the cookie and the unescape() function when you read the cookie.
The expires attribute
This sets the expiry time and date of the cookie. If omitted then the cookie expires at the end of the browser session (i.e. when the browser is closed).
The path attribute
This determines the path to web pages that are allowed access to the cookie. For example if only web pages within the products directory should have access to the cookie then the path would be /products.
In the example above the path / means the cookie may be accessed by any web page or directory within the document root.
If omitted then the cookie can only be accessed by web pages in the same directory as the web page that created it or by pages within any subdirectories.
The domain attribute
Setting this allows the cookie to be accessed by any web page on the domain, even if it's held on a different server, as well as any subdomains.
If omitted then the cookie may only be accessed by web pages on the server from which the cookie was created.
Using the escape() Function
If the cookie value includes commas, semicolons or whitespace then use the escape() function and concatenation to construct the string.
The example below sets an expiry time and date and can be accessed by any web page in same directory as the script creating the cookie.
To read the contents of a cookie you read the cookie property. This returns a name value pair in the form name = value where name is the name of the cookie and the value is the cookie string.
If there is more than one cookie then the string is a list of name value pairs separated by semicolons.
The value returned does not include any of the attributes set when the cookie was created, such as expiry etc.
If you used the escape() function to write the cookie then use the unescape() function to read it.