Monday, May 26, 2008

ASP Cookies


A cookie is a temporary file used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.


Why is a cookie used?
A cookie (persistent) enables a website to remember you on subsequent visits, speeding up or enhancing your experience of services or functions offered.
For example, a website may offer its contents in different languages. On your first visit, you may choose to have the content delivered in French and the site may record that preference in a persistent cookie set on your browser. When you revisit that site it will use the cookie to ensure that the content is delivered in French.


Creating a Cookie:

Response.Cookies("firstname")="Alex"


Properties:
1. Domain: This is the domain that the cookie originated from. It is set by default to the domain in which it was created but it can be altered.
Example: Response.Cookies("name").Domain = http://www.cookiemonster.com/
2. Expires: There are 2 ways.
a) You can use the current date and add or subtract days
Response.Cookies("name").Expires = Date + 365
b) You can set it to a specific date

Response.Cookies("name").Expires = #May 10,2002#

Note: To expire the session enabled with cookies, Give current date.

Example: Response.Cookies("name").Expires = Date OR Date-1
3. Path: This specifies in more detail the exact path on the domain that can use the cookie.
Response.Cookies("name").Path = "/this/is/the/path"
4. Secure: If set, the cookie will only be set if the browser is using secure sockets or https:// to connect.
Response.Cookies("name").Secure = True


Dictionary Cookie OR Cookies with Keys: It is a cookie that can hold multiple values.
Example:
Response.Cookies("name")("first") = "John"Response.Cookies("name")("last") = "Smith"


How to know if the cookie has keys?
Ans: With the Haskeys property.
Example:

dim x,y

for each x in Request.Cookies

if Request.Cookies(x).HasKeys then

for each y in Request.Cookies(x)

response.write(x & ":" & y & "=" & Request.Cookies(x)(y))

next

else

Response.Write(x & "=" & Request.Cookies(x))

end if

next

Note: There are limits on how much data you can put on a clients browser. Most browsers allow you to place 20 cookies per domain at a maximum of 4k each.

Types of cookies:
1. Persistent: Persistent cookies are stored on your computer hard disk. They stay on your hard disk and can be accessed by web servers until they are deleted or have expired. Persistent cookies are not affected by your browser setting that deletes temporary files when you close your browser.
2. Non-Persistent: Non-persistent cookies are saved only while your web browser is running. They can be used by a web server only until you close your browser. They are not saved on your disk.

No comments: