Wednesday, 29 September 2010

ASP: Do you like cookies?

   


People don't like cookies, antivirus and anti spyware applications hate tracking cookies, everybody is scared to death by cookies. In the end they are just cookies... maybe poisoned cookies, maybe just valuable in some situations. If you're dealing with local web applications, you might find the use of cookies quite interesting, especially when you need to store temporary information such as log-in user name or date stamp.
Provided that the client is accepting cookies, storing and retrieving cookies is quite easy and straightforward.
To set a cookie, just insert this code at the beginning of you page:
<%
Response.Cookies("nameofthecookie") = "value"
%>
You can even determine its expiration date;
<%
Response.Cookies("nameofthecookie").Expires = Date + 30
%>
In the example I set the expire date to 30 days from today. If you don't set an expire date, your cookies will last until the browser is closed.
I can even set a precise date:
<%
Response.Cookies("nameofthecookie").Expires = #Dec 31,2010#
%>
To retrieve the cookies value, use:
<%
Dim value
value = Request.Cookies("nameofthecookie")
if value <> "" then
  response.write value
end if
%>
You can use keys in cookies. That is a cookie that stores multiple information:
<%
Response.Cookies("nameofthecookie")("key1") = "value1"
Response.Cookies("nameofthecookie")("key2") = "value2"
response.write Request.Cookies("nameofthecookie")("key1")
response.write Request.Cookies("nameofthecookie")("key2")
%>
Last code snippet! If you want to check if a browser is accepting cookies, use this:
<%
Response.Cookies("nameofthecookie") = "value"
cook = Request.Cookies("nameofthecookie")
if cook="" then
  response.write "<script language=""javascript"" type=""text/javascript"">alert('Your cookies are disabled. Please enable cookies for full functionality.');</script>"
end if
%>
And that's all! Don't eat too much...

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.