This example creates a cookie that counts the number of times each person has visited your site. It will also expire in 10 days from thier last visit.
Here's the code:
Code:
<%
response.cookies("MyCookie").Expires = date + 10
num=request.cookies("MyCookie")
if num = "" then
response.cookies("MyCookie") = 1
else
response.cookies("MyCookie") = num + 1
end if
%>
First things first. The <% and %> indicate where the code starts and ends, so the server knows what to do with what, and where.
response.cookies("MyCookie").Expires = date + 10
Next, create the cookie, and make it expire 10 days from now. Also, we will call the cookie MyCookie.
num=request.cookies("MyCookie")
This line asks to open MyCookie, and then fill the value "num" with whaterever's inside.
if num = "" then
Now, if this is the persons first visit to the page, the cookie will be empty (Oh No!). Now, we can't have that. Otherwise, there would be no point.
So, this IF checks to see if it is empty
response.cookies("MyCookie") = 1
If the cookie was empty, then we get to this line. This will put the number "1" in the cookie.
response.cookies("MyCookie") = num + 1
If it wasn't empty (else) then it goes to this line, which will incriment (increase, add 1 to it, whichever you prefer) the number it got from the cookie by 1, and then save the new number to the cookie after.
There you go, you know how to get information from, a cookie and put some in one. Now, see the full code example below to see some other things you can do with a cookie. It's fairly straight forward.
Except for maybe this, which I'll explain here:
<%response.write(num)%>
Put that in your page, wherever you want the cookies value displayed, and it will do so.
- Sarlok
Code:
<%
response.cookies("MyCookie").Expires = date + 10
num=request.cookies("MyCookie")
if num = "" then
response.cookies("MyCookie") = 1
else
response.cookies("MyCookie") = num + 1
end if
%>
<html>
<body>
<%if num="" then%>
If the cookie was empty, we will see this lovely welcome message.<br>
Welcome! This is the first time you have visited my cookie page.<br>
<%else%>
If it wasn't empty, we will see this.<br>
Welcome back. You've been here <%response.write(num)%> time(s).<br>
<%end if%>
</body>
</html>