The values of Cookies are much more complex than those of other ASP collections such as Form and ServerVariables. A cookie is a small piece of text stored on the client system by the browser and sent with each request to the server in the domain to which they apply.
ASP makes it easier to apply cookies. You can obtain all cookie values sent with the request from the Cookies collection of the Request object, and you can create or modify cookies and send them back to the user through the Cookies collection of the Response object.
Cookies contain information that can be constructed in two ways. Single-value cookies provide their values to code through a general ASP-like collection. However, each member of a collection may itself be a collection, and cookies containing this information are called multi-value cookies.
Creating a single-value cookie is relatively simple, as follows:
Response.Cookies("item-name") = "item-value"
To create a multi-value cookie, you can use the following command:
Response.Cookies("item-name" )("sub-item-name") = "sub-item-value"
sets the domain and path of cookie application and its validity period. We use:
Response.Cookies("item-name").domain = "domain-url"
Response.Cookies(“item-name”).path = “virtual-path”
Response.Cookies("item-name").expires = #date#
Usually, the client only sends the cookie to the server with the request when making a request for a page in the directory where the cookie was created. By specifying the path attribute, you can specify where in the site this cookie is valid and the cookie will be sent with the request. If the cookie is sent with page requests for the entire site, set path to "/".
If the Expires attribute is not set, the cookie will be automatically eliminated when the current browser instance is closed.
Note that the cookie is already created when we send any output to the browser. Because, these cookies are part of the page's HTTP header.
In ASP 3.0, the default state of buffering is on, and no output is sent unless Response.Flush is used to specify this or the page has reached the end. This means that the code that creates the cookie can be anywhere on the page, and it can be executed until any output is "flushed" to the client.
To read existing cookies, use the Request.Cookies collection. Items within can be accessed individually, similar to the method used to create them.
StrSingleValue = Request.Cookies("item-name")
StrSubItemValue = Request.Cookies("item-name")("sub-item-name")
Note that the Request.Cookies collection (like all other Request collections) is read-only. The Response.Cookies collection is write-only. In fact, you can access the names of a series of cookies in this collection, but not their values.
Traversing the Cookies Collection
In order to use the Cookies collection more conveniently, you can use the additional attribute named Haskeys. If the accessed cookie is itself a collection, that is, it is a multi-valued cookie, this will return True. Using the Haskeys property, you can iterate through the complete Request.Cookies collection to get a list of all cookies and their values.
For Each objItem In Request.Cookies
If Request.Cookies(objItem).HasKey Then
'Use another For Each to iterate all subkeys
For Each objItemKey in Request.Cookies(objItem)
Response.Write objItem & “(“ & objItemKey & “) = “_
& Request.Cookies(objItem)(objItemKey) & “<BR>”
Next
Else
'Print out the cookie string as normal
Response.Write objItem & “ = ” & Request.Cookies(objItem) & “<BR>”
End If
NextThis
is very similar to the previous complex code that extracts multiple values from the Request.Form collection. But you can use the Haskeys attribute here to determine whether each entry is a set. In the Form example, the Request.Form(item_name).Count property must be queried because the members of the Form collection (and all other collections except cookies) cannot be real collections. ASP just does the "behind the scenes" work and gets the value of each multi-entry collection.
Differences between Form and QueryString
After understanding the techniques for accessing various ASP collections, another question needs to be solved: What is the difference between Form and QueryString collections? If you are going to use ASP, you should undoubtedly be aware of this difference, but you need to refer to the way HTTP works to re-understand and understand them.
There are two general methods for requesting a page or other resource from a web server via HTTP. You can use the GET method to obtain the resource directly, or you can use POST to pass the value to the corresponding resource. The GET method is the default. You can look at an example of an HTTP request earlier in this chapter:
7/8/99 10:27:16 Sent GET /Store/Download.asp HTTP/1.1
If you put one or more paired names When the / value is appended to the URL of the requested page, it becomes the requested query string and is provided to the ASP page in the QueryString collection. Clicking a hyperlink on a Web page, email message, or other document, or entering the address in the browser's address bar and pressing Enter, or clicking the Links or Favorites button in the browser, all use the GET method.
Therefore, the only way to pass values to ASP in these actions is through the QueryString collection, appending the values to the URL.
Values that appear in the Request.QueryString collection and are accessed work in the same way as the Form collection instance we saw earlier. A combination of URL and query string:
http://mysite.com/process_page.asp?FirstName=Priscilla&LastName=Descartes
The value provided in the QueryString collection can be accessed as follows:
strFirstName = Request.QueryString("FirstName") 'Return "Priscilla"
strLastName = Request.QueryString("LastName") 'Return "Descartes"
strRaw = Request.QueryString
'Return "FirstName=Priscilla&LastName=Descartes"
GET and POST methods of the form.
When using the <FORM> segment in a page, you can set the METHOD attribute value of the opened FORM tag to "GET" or "POST". The default value is "GET". If "GET" is used or its attribute is omitted, the browser binds this value to all controls on the page, becomes a query string, and is attached to the URL of the requested page.
When this request arrives at the Web server, its value is provided by ASP's Request.QueryString collection. However, if you set the METHOD attribute to "POST", the browser wraps the value into the sending server's HTTP header and provides it to ASP through the Request.Form collection.
By the way, the POST method can be used in all HTML forms. However, there are certain limitations on the URL string length of the browser or server. Therefore, appending long strings may cause overflow and some string characters to be truncated. At the same time, the query string appears in the browser's address bar and in all saved links and favorites. Not only that, but it also exposes unwanted values in the HTTP request when passing through the web server, and it may also appear in the log files of your server and other routing servers. Values in HTTP request headers are rarely visible and do not appear in log files.
A small problem to note with using the POST method is that when the user re-downloads the <FORM>, the form's values are no longer retained and their values are empty and must be re-entered. However, when attached to a URL, the value is stored as a link and will be retained and therefore will appear in all requests where the URL is combined with the string. This may be an advantage or disadvantage depending on the application. (Some browsers can automatically retain values on a page within a certain range on the client).
Another point is that the combination of URL and query string cannot contain any spaces or other illegal characters, otherwise Navigator and some other browsers will have problems. Illegal characters are those used to separate the URL and the query string, such as "/", ":", "?" and "&" (IE can automatically convert spaces into the correct format - the plus sign "+", But other illegal characters cannot be processed)
Use of cookies in ASP
In this section we will learn the various techniques that provide collections, methods and properties for use by ASP code.
1) User details are stored in cookies.
Cookies can be used to store two types of values: values that we do not want to save when the browser is closed (such as user registration information) and values that we want to retain when the user visits the site. In each case the cookie's value is available to ASP for every page request from the user's browser.
However, you need to remember that the cookie will only be sent to the server when a request is made for a page within the virtual path (path) in the cookie. By default, if the value of path is not set in the cookie, its value is the virtual path of the page that created the cookie. In order for a cookie to be sent to all pages of a site, path="/" needs to be used.
Here is an example. From a custom Login page, the user's registration information is stored in a cookie. Since there is no application validity period, the cookie value is only retained until the browser is closed:
...
Request.Cookies(“User”)(“UID”) = “<% = Request(“UserName”) %>”
Request.Cookies(“User”)(“PWD”) = “<% = Request(“Password”) %>”
Request.Cookies(“User”).Path = “/adminstuff” 'Only applies to admin pages
...
this cookie will now be found on every page that the user requests from the adminstuff directory or its subdirectories. If it does not exist, you can redirect the user to the registration page:
If (Request.Cookies("User")("UID") <> "alexhomer") _
Or (Request.Cookies(“User”)(“PWD”) <> “secret”) Then
Response.Redirect “login.asp?UserName=” & Request.Cookies(“User”)(“UID”)
End If
...
Since the username in the cookie is placed in the URL query string of Response.Redirect, if an error occurs when entering the password and you want the user to not have to retype the username, you can use it in the login.asp page:
<FORM ACTION=”check_user.asp” METHOD=”POST”>
<INPUT TYPE=”TEXT” NAME=”UserName”
VALUE=”<% = Request.QueryString(“UserName”) %>”><P>
<INPUT TYPE=”SUBMIT” VALUE=”LOGIN”>
</FORM>
2) Modify existing cookies
You can use ASP to modify existing cookies, but you cannot modify only one value in the cookie. When updating a cookie in the Response.Cookies collection, the existing value will be lost. We can create a cookie with the following code, which can be used:
Response.Cookies("VisitCount")("StartDate") = dtmStart
Response.Cookies("VisitCount")("LastDate") = Now
Response.Cookies("VisitCount")("Visits") = CStr(intVisits)
Response.Cookies("VisitCount").Path = "/" 'Apply to entire site
Response.Cookies("VisitCount").Expires = DateAdd("m",3,Now)
If you want to update the values of Visits and LastDate, you must first not change all the values, and then rewrite the entire cookie:
datDtart = Response .Cookies("VisitCount")("StartDate")
intVisits = Response.Cookies("VisitCount")("Visits")
Response.Cookies("VisitCount")("StartDate") = dtmStart
Response.Cookies("VisitCount")("LastDate") = Now
Response.Cookies("VisitCount")("Visits") = Cstr(intVisits)
Response.Cookies(“VisitCount”).Path = “/”
Response.Cookies("VisitCount").Expires = DateADD("m",3,Now + 1) and as with almost all other Response methods and properties, it should be done before writing anything (i.e. opening a <HTML> tag or any text or other HTML) to the response.