Access and update cookies

Source: Internet
Author: User
Tags servervariables
Access and update cookies
The value of cookies is much more complex than that of other sets of ASP (such as form and servervariables. Cookie is a small piece of text stored by the browser on the client system, and each request is sent to the server in the domain they are applied.
ASP makes the application cookie easier. You can obtain all the cookie values sent along with the request from the cookie set of the request object, and create or modify the cookie, send it back to the user through the cookie set of the response object.
Cookie contains information constructed in two ways. A single-value cookie provides its value Code Is through a general ASP class set. However, each member of a set may also be a set. Cookies containing such information are called multiple-value cookies.
Creating a single-value cookie is simple, as shown below:
Response. Cookies ("item-name") = "item-value"
To create a multi-value cookie, run the following command:
Response. Cookies ("item-name") ("sub-item-name") = "sub-item-value"
Set the domain and path of the 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 #
Generally, the customer sends the cookie request to the server only when making a request to the page in the cookie creation directory. By specifying the path attribute, you can specify where the cookie is valid on the site, and the cookie will be sent with the request. If the cookie is sent along with the page request to the entire site, set
PATH is "/".
If the expires attribute is not set, the cookie is automatically cleared when the current browser instance is closed.
Note that a cookie has been created when we send any output to the browser. Because these cookies are part of the HTTP header of the page.

In ASP 3.0, the buffer is enabled by default, and no output is sent, unless response. Flush is used to define this job or the page is reached the end. This means that the cookie creation code can be executed at any location on the page until any "refresh" (flush) is output to the client.
Line.

To read existing cookies, use the request. Cookies set. You can access the projects in them by using methods similar to those used when creating them.
Strsinglevalue = request. Cookies ("item-name ")
Strsubitemvalue = request. Cookies ("item-name") ("sub-item-name ")
Note that the request. Cookies set (the same as all other request sets) is read-only. Response. The cookie set is only written. In fact, you can access the names of a series of cookies in this set, rather than their values.

Traverse cookies
To make it easier to use cookies, you can use the additional attributes named haskeys. If the accessed cookie is a set, that is, a multi-value cookie, true is returned. By using the haskeys attribute, You can traverse the complete set of request. cookies to obtain the 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
Next
This is very similar to the complex code that extracts multiple values from the request. Form set. However, the haskeys attribute can be used to determine whether each entry is a set. In the form example, the request. Form (item_name). Count attribute must be queried. This is because the form set (and all other sets except cookie) members cannot be real sets. ASP only works behind the scenes and obtains the values of each set of multiple entries.

Difference between form and querystring
After learning about the technology used to access various ASP collections, another problem that needs to be solved is: What is the difference between form and querystring collections? If you are preparing to use ASP, you should be clear about the difference, but you need to refer to the HTTP work method to re-understand and understand them.
There are two common methods to request pages or other resources from the Web server over HTTP. You can use the get method to directly obtain the resource, or use post to pass the value to the corresponding resource. The get method is default. You can refer to an HTTP request instance earlier in this chapter:
7/8/99 10:27:16 sent get/store/download. asp HTTP/1.1
If one or more pairs of Names/values are attached to the URL of the Request page, the query string of the request is changed and provided to the ASP page in the querystring collection. Click the hyperlink of the web page, email message, or other documents, enter the address in the address bar of the browser, press enter, or click
The links or Favorites button, all of which must use the get method.
Therefore, the only way to pass values to ASP in these actions is to add the values to the URL through the querystring set.
The value that appears in the request. querystring collection and is accessed. It works in the same way as the form set instance. Combination of URL and query string:
Http://mysite.com/process_page.asp? Firstname = Priscilla & lastname = Descartes
You can use the following method to access the values provided in the querystring collection:
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 you use

segments on a page, you can set the method attribute value of the form flag to "get" or "Post". The default value is "get ". If "get" is used or its attributes are omitted, the browser binds the value to all controls on the page to form a query string and attaches it to the URL of the requested page.
when the request arrives at the web server, its value is provided by the ASP request. querystring set. However, if the method attribute is set to "Post", the browser packs the value into the HTTP header of the sending server and provides it to ASP through the request. Form set.
the POST method can be used in all HTML forms. However, the length of the URL string of the browser or server is limited. Therefore, long strings may cause overflow and some character strings are truncated. Meanwhile, the query string appears in the address bar of the browser and all the saved links and favorites. In addition, the value that you do not want to display in the HTTP request when using the Web server may also appear in the log files of your server and other routing servers. The value in the HTTP request header is rarely visible and does not appear in the log file.
when using the POST method, note that the form value is not retained when the user downloads again. The value of the form is blank and must be re-entered. However, when it is attached to a URL, its value is stored as a link and will be retained. Therefore, it will appear in all requests that combine URLs with strings, this may be an advantage or a disadvantage, depending on the application (Some browsers can automatically retain the value on a page within a certain range on the client ).
the combination of a URL and a query string cannot contain any space or other illegal characters. Otherwise, navigator and other browsers may encounter problems. Invalid characters are the parts used to separate URLs and query strings, such as "/", ":", and "?". And "&" (ie can automatically convert spaces to the correct format ?? +, But other illegal characters cannot be processed ). The ASP Server Object provides the urlencode method to handle this transformation. The following sections will discuss the relevant content.

View request and response object content
So far, I have discussed some theoretical issues and have not listed any special examples. Because the content that has been discussed is closely related to each other in most cases. However, this book provides a series of instance pages for this chapter to illustrate most of the attributes of the request and response objects. The instances mentioned in the application can understand these pages, modify them accordingly, and use them as test instances.
The sample code of this chapter and all other chapters is provided to you. You can download the sample code from the wrox press site.
Http://webdev.wrox.co.uk/books/2610
Http://www.wrox.com/Store/Details.asp? Code = 2610
You must first install the instance in the subdirectory of wwwroot on the Web server, and then access the chapter02 subdirectory using a browser, using:
Http: // your_server_name_or_ip/subdirectory_name/chapter02/default. asp
Your_server_name_or_ip/subdirectory_name is the local path for installing and downloading files.
1. view request object members
This provides a menu containing a page selection to test the request and response objects. First, select using the request object, as shown in:

Display an example of an HTML form that contains pre-set values. You can edit these values as you wish and click "Submit.

This will open a page, as shown in, showing all the content of the set and totalbytes attributes. The first screen displays form, querystring, and cookies.
Set.

Note: If the value of the HTML control is edited on the form page, different values may be displayed on the page of the reader's computer for the cookie set and other sets.
The "Form collection" section shows how the values of the HTML control on the form are represented in the ASP request. Form collection. You can also use the original <form> page (named request_form.asp) to test and detect the HTML of the created form and how to associate it with the corresponding value.
This page is followed by a set of clientcertificate. This is empty because the server does not require the client to provide a certificate. The following is the servervariables set. The screen chart shows the useful values contained in the set.

In the appendix after this book, you can find a list of all servervariables set members and descriptions of their values. However, you can see these Members from the HTTP header sent by the client on the request page as discussed earlier. When the request is received, the web server also adds some of its own values to the collection, as shown in the preceding figure running on the page created in IIS 5.0.
1) how the page works
To create this page, we use the exactly the same code we see in the previous sections on the form set and how to access its values. For example, to traverse all sets (except request. Cookies), use:
For each objitem in request. collection_name
Response. Write objitem & "=" & request. collection_name (objitem) & "<br>"
Next
To traverse the cookie set, you can use:
For each objitem in request. Cookies
If request. Cookies (objitem). haskeys then
'Use another for... each to iterate all keys of dictionary
For each objitemkey in request. Cookies (objitem)
Resonse. 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
Next
To obtain the totalbytes attribute, you can simply use:
Request. totalbytes = <% = request. totalbytes %> <p>
You should note that some values in the two sets are not directly obtained from the HTML control of the form. The querystring set contains two values named chapter and sample, as shown in:

to create these two values in the request, a string is attached to the URL of the Action attribute of the form. This is acceptable. The work method is similar to the href attribute attached to a element. The query character value appears in the querystring collection, and the Form Control Value of the post object appears in the form set.


to prevent non-IE browser errors, the space in the query string must be replaced by the plus sign "+". The reader will see more of this in the urlencode method of the server object in Chapter 4th.
2) create a client cookie
to ensure that at least some values appear in the request. Cookies set, add some client script code to the original page request_form.asp. Create a multi-value cookie named visitcount. Another cookie is created by another page and already exists in the browser. As shown in, the reader can see another cookie.

This is a client code that sets the cookies attribute of the document object when the form is loaded:
<Script language = "JavaScript">
<! --
Paiet. Cookie = 'visitcount = visits = 3 & lastdate = 6% 2f4% 2f99 + 10% 3a10% 3a13 + am ';
// -->
</SCRIPT>
In addition, the content must be encoded so that it can be correctly transmitted to the server (the same rule applies to attaching a query string to a URL ). In Chapter 4th, you will learn more about the urlencode method of the server object.
2. view the response object Member
Return to the original default of the chapter02 instance. ASP page, this time select the "using the response object" link, this page shows the response object set and attribute content, and provides links to all response object methods.
Is to use the browser netsape communicator 4.61 screen, to prove that the use of pure server and cross-platform compatibility technology. Note that the cookie set is created for the response object. Only the cookie name is displayed, but its value is not displayed. When you browse this page, you may not get a cookie or get a different cookie from this page. (Because netsape communicator 4.61 is not installed on beans, ie5.5 is still used for display. There is no difference)

Various response attributes indicate the information to be used to create an HTTP header. Other parts of the HTTP header page (HTML and text content) are sent to the client. Some of these attributes and all response object methods are linked, allowing readers to open another page to display their usage. We will return to these pages later.
The properties on the page are created by reading the corresponding properties and inserting them into the page. Because these are dynamic links, you can select them using the <A> element.
<A href = "headers/expiretet_form.asp"> response. cachecontrol </a>
= <% = Resposne. cachecontrol %> <br>
Each method is linked through the <A> link element. The only complex part of the page is the response. Cookies set. You can only access cookies to read the values in the request. Cookies set. When you access the response. Cookie set, you must end all references to it before sending any output to the client. Therefore, in the upper part of the page, the HTML of the page created by traversing the set is placed in a local string variable.
Strcookies = ""
'We can only read the key names and not the values because
'The response. Cookies collection is 'write only'
For each objitem in response. Cookies
If response. Cookies (objitem). haskeys then
'Use another for each to iterate all subkeys
For each objitemkey in response. Cookies (objitem)
Strcookies = strcookies & objitem & "(" & objitemkey & ") <br>"
Next
Else
'Print out the cookie as normal
Strcookies = strcookies & objitem & "<br>"
End if
Next
Then insert the result on the appropriate page.
<P> <Div class = "Subhead"> the response. Cookies collection </div>
<I> <a href = "Cookies/setcookies. asp"> response. Cookies </a>
Is a write-only collection so the values cannot be displayed </I> <br>
<% = Strcookies %>

Use of cookies in ASP
On the previous page, some sets, attributes, and methods have been linked to other pages to display the features of the request and response objects, we will study this content in the rest of this chapter, and we will learn the various technologies that provide the collection, methods, and attributes for ASP code to use.
Before this chapter, we have seen how to use request. cookies and response. cookies set to create and read cookies. When you click any "cookies" link on the two pages above, this page contains ASP code that sets the values of three cookies, the executed code is displayed on the page, as shown in:

When you click "show cookies", the cookie content is displayed. This is obtained by traversing the request. Cookies set, which is exactly the same as the method used on the previous page, as shown in:

The screen shows the result of running the code that sets the cookie value. Other Cookies stored in computer systems may be displayed. However, if you close the browser and re-open the browser, and then run the page showing the cookie, all the cookies except timedcookie will be lost because only the timedcookie has a valid setting, when the browser is closed, others will disappear automatically.
1) storing user details in cookies
You can use cookies to store these two types of values: values that we do not want to save when the browser is closed (for example, user registration information) and values to be retained when the user accesses the site. In each case, the cookie value is available for ASP for each page request from the user's browser.
However, you must remember that a cookie is sent to the server only when a request is sent to a page in the virtual path in the cookie. If the path value is not set in the cookie, the value is the virtual path of the page on which the cookie is created. To send a cookie to all pages of a site, use Path = "/".
Here is an instance. From the custom login page, the user registration information is stored in a cookie. Because there is no application validity period, the cookie value is retained only before closing the browser:
...
Request. Cookies ("user") ("uid") = "<% = request (" username ") %>"
Request. Cookies ("user") ("PWD") = "<% = request (" password ") %>"
Request. Cookies ("user"). Path = "/adminstuff" 'only applies to admin pages
...
Now, the cookie can be found on every page requested by the user from the adminstuff directory or its subdirectory. 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
...
Because the cookie user name is placed in the URL query string of response. Redirect, if an error occurs during Password Input and you do not need to re-type the user name, you can use it on 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 an existing cookie, but cannot modify only one value in the cookie. When updating a cookie in the response. Cookies set, the existing value will be lost. You can use the following code to create a cookie:
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 do not need to change all values first, 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 for almost all other response methods and attributes, this should be done before writing any content (that is, opening the <HTML> tag or any text or other html) to the response.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.