Cookies are very helpful for certain kinds of sites.
Take for example a shopping basket style site such as a book store.
After picking a book, the visitor wants to continue shopping
without remembering what's in the basket.
Not only must the server keep track of each book that the visitor picks
but it must also keep a visitor's books separate from other visitors.
So far, we have not discussed any ways of uniquely identifying visitors.
Without cookies, the site must put a key number for a visitor
into every link and every form in the site
and then store that key with the books that visitor picks.
It's not easy yet many sites do this in order to support browsers that cannot keep cookies.
Today, such browsers are quite marginal, one to three percent at most.
Cookies simplify this process considerably.
Once a cookie is sent to a browser, it keeps coming back with every request.
So if the site sends a different cookie value to each visitor,
that value can be used as a key to the visitor's basket.
The cookie must be sent as part of the header.
The header is a set of lines sent before any HTML.
As a rule, headers are separated from the HTML by one blank line.
At least one header line is required that identifies the format.
The Getting Started examples all use Content-Type: text/html.
A script that sends this and a cookie might look like this:
Send CGI_CONTENT_TYPE_TEXT_HTML
Send SetCookie("Color", "Red")
Send vbCrLf
Send "<HTML>Hi there!</HTML>"
Here is a simple yet more complete example.
It counts each visit a visitor makes to this script.
Public Sub Main()
Dim Visits As Long
On Error GoTo Trap
Call LoadRequest
Visits = Int("0" & GetRequest("Visits")) + 1
Send CGI_CONTENT_TYPE_TEXT_HTML
Send SetCookie("Visits", Visits, "1/1/2020")
Send vbCrLf & "<HTML><BODY>"
Send "This is visit number " & Visits
Send " for you.</BODY></HTML>"
End
Trap:
Call ErrorHandler
End
End Sub
For more details on the SetCookie instruction,
jump to SetCookie.
For yet another example, download the vbshop sample VBWeb application,
find the SetCookie instruction,
and follow the logic around it.
|