Cookie details!

Source: Internet
Author: User
Tags allkeys cookie names

In the age of new technology, cookies seem to have been forgotten. however, it is still indispensable in web design. Here I have summarized its application for many years. It may not be the most comprehensive, but it must be the most practical.
Cookies are no longer irreplaceable and not essential. Therefore, they have lost a lot of color. Many people describe them as a chicken ribs. however, many of our technologies seem to be boring and indispensable if all of them are judged by this. in my opinion, it is better to make less comparisons and make more choices, so there will be more confusions, and my mind is not calm. It is useful and tasteless to look at anything. I feel that many technologies are easy to use and naturally have a taste.
To sum up, there are several possible reasons for "food is tasteless.
(1). Insecure. This is the most direct cause, because cookies are stored on the client computer, so they are easily modified, resulting in applications when accessing the server. Program Or other security issues.
(2 ). this is one of the most practical reasons for severely limiting the size of the transmitted content. Most browsers limit the size of the cookie, which generally cannot exceed 4096 bytes. Therefore, the transmitted content is limited.
(3) users can control the enabling and disabling of cookies: This is one of the most helpless reasons. When users set their browsers to stop receiving cookies, it will become useless.
(4 )........
Although it is already a chicken rib, it is a pity to discard it because of the following reasons.
(1 ). easy to use: because it is too simple to use, it can survive until today, although many people complain every day, while secretly using it. cookie is simple because it is the simplest Text Structure of the index key value. It is very convenient to read and set data.
(2 ). does not occupy any server resources: the cookie generation principle is that after the server is created, it is entered to the client along with the webpage and resides on the client computer. Therefore, it does not need to occupy any server resources.
(3 ). the validity period can be set at will: You can set the validity period as you like to make it quite useful. You can set the cookie to disappear when the browser ends the access, or set the expiration time for a specific feature, even permanently stored on a computer.
(4 )........
Okay, it's a blessing. People have their own aspirations. here I have summarized the functions and usage of cookies in various aspects of web design. the sentence may not be the most comprehensive, but it must be the most practical. share with you. okay. Here we will start with the simplest use.

1. What values can a cookie store?
Only personal identifiable information can be stored in cookies. personal identifiable information refers to information that can be used to identify or contact users. for example, user name, email, home address, etc. it must be emphasized that such identifiable information must be non-confidential or important.

2. Use the cookie object to save and read client information.
To store a cookie variable, you can use the cookie set of the response object. The syntax is as follows:
Response. Cookies [varname]. value = value;

Where varname is the variable name.
To retrieve a cookie, you can use the cookie set of the request object and return the specified Cookie set. The syntax is as follows:
Variable name = request. Cookies [varname]. value;
For example, use cookie to operate the Client IP address. Code As follows:

// Save client information
String userip = request. userhostaddress. tostring (); // obtain the Client IP Address
Response. Cookies ["ip"]. value = userip; // Save the Client IP address in the cookie object
Response. Cookies ["ip"]. expires = datetime. maxvalue; // design the expiration time of cookies

// Read
Response. Write (request. Cookies ["ip"]. Value); // read the Client IP address value from cookies


3. encrypt data in cookies
To prevent user information from being stolen by others and enhance the security of the website, data in cookies must be encrypted. the encryption code is as follows:

String data = "encrypt data in cookies. ";
Response. Cookies ["data"]. value = formsauthentication. hashpasswordforstoringinconfigfile (data, "MD5 ");
Response. Write (request. Cookies ["data"]. value );


4. Use a cookie object to pass values between pages.
The method for transferring values between pages using cookie objects is the same as that for transferring values between pages using session objects, but the two are essentially different. that is, the cookie is stored on the client, and the session is stored on the server. when using cookies, you must also use the Asp.net built-in Object Request.
The code for transmitting information using a cookie object is as follows:

If (txtname. Text = "A" & txtpassword. Text = "")
{
Httpcookie newcookie = new httpcookie ("username ");
Newcookie. value = txtname. Text. Trim ();
Response. appendcookie (newcookie );
Server. Transfer ("B. aspx ");
}
Else
{
Response. Write ("<SCRIPT> alert ('logon failed! '); </SCRIPT> ");
}


On the target page (B. aspx), receive the value from the cookie object and display it on the interface. The Code is as follows:

Label1.text = request. Cookies ["username"]. value. tostring ();


5. Use cookies to verify user logon.
To use cookies to verify user login, you must first save the login information in the cookie object, and then read and verify the information.
For example, when a user is registered (of course, in many cases, the user can exit the system) and save the user and user password in the cookie object. The Code is as follows:

Response. Cookies ["savedlogin"] ["username"] = txtname. Text. Trim ();
Response. Cookies ["savedlogin"] ["userpwd"] = txtpassword. Text. Trim ();
Response. Cookies ["savedlogin"]. expires = datetime. Now. adddays (1 );
Response. Write ("<SCRIPT> alert ('registration successful! '); Location = 'default. aspx'; </SCRIPT> ");

When a user logs on, the system first checks whether the cookie object is invalid. If the cookie object is not valid, it checks whether the information entered by the user is consistent with the information saved in the cookie object. If the information entered by the user is consistent, to perform other operations. the Code is as follows:


If (request. Cookies ["savedlogin"] = NULL)
{
Response. Write ("<SCRIPT> alert ('cookie expired! '); Location = 'default. aspx'; </SCRIPT> ");

}
Else
{
If (txtname. Text = request. Cookies ["savedlogin"]
["Username"]. tostring () & txtpassword. Text =
Request. Cookies ["savedlogin"] ["userpwd"]. tostring ())
{
Session ["username"] = txtname. Text. Trim ();
Response. Redirect ("navigatepage. aspx ");
}
Else
{
Response. Write ("<SCRIPT> alert ('logon failed! ')");
}
}


6. Create and access cookie objects with multiple key values.
The application of multi-key values is actually a "classification" idea, storing a certain type of information together. The implementation method is
You can use the response object to create cookies with multiple data values. The syntax is as follows:
Response. Cookies ["cookiename"] ["keyname"] = "Cookie's relative index key value ";
For example, use a multi-key value to save the user name and password. The Code is as follows:


If (txtname. Text = "A" & txtpassword. Text = "")
{
Response. Cookies ["userinfo"] ["username"] = this.txt name. Text. Trim ();
Response. Cookies ["userinfo"] ["userpwd"] = this.txt password. Text. Trim ();
Response. Redirect ("B. aspx ");


}
Else
{
Response. Write ("<SCRIPT> alert ('logon failed! '); </SCRIPT> ");
}

When a webpage request is sent, the browser sends the cookie information to the server. on the server side, you can use the request object to access the data value in the cookie. The syntax format is as follows.
Method 1: directly retrieve data values
Stirng str1 = response. Cookies ["cookiename"] ["keyname"];
Method 2: retrieve data values using Indexes
String str2 = response. Cookies ["cookiename"]. Values [1];
Method 3: retrieve the data value using the index key name.
String str3 = response. Cookies ["cookiename"]. Values ["keyname"];


7. traverse the cookie set
Here is an example of how to traverse the client's cookie object and display the content value of all the client's cookie objects. The Code is as follows:

String [] cookiename, keyname; // defines two arrays to store names
Httpcookiecollection mycookiecollection; // defines the cookie set object
Httpcookie mycookie; // defines the cookie object
Mycookiecollection = request. Cookies; // retrieve the client's cookie
Cookiename = mycookiecollection. allkeys; // get all cookie names in the Set
For (INT I = 0; I <= cookiename. getupperbound (0); I ++) // loops each cookie
{
Mycookie = mycookiecollection [cookiename [I];
Response. write ("Name of the cookie:" + mycookie. name + "<br>" + "Cookie expiration time:" + mycookie. expires + "<br> ");
Response. Write ("all content values in the cookie are as follows:" + "<br>"); // output the cookie content
Keyname = mycookie. Values. allkeys;
For (Int J = 0; j <= keyname. getupperbound (0); j ++)
{
Response. Write (keyname [J] + ":" + mycookie [keyname [J] + "<br> ");
}
Response. Write ("<HR> ");


8. Set the lifecycle of COOKIE variables
Although the cookie object variables are stored on the client computer, they are not always invisible. The designer sets the cookie object validity date in the program. The syntax is as follows:
Response. Cookies ["cookiename"]. expires = date;

If no validity period (expires attribute) is specified, the cookie variable will not be saved. When the browser is closed, the cookie variable will also disappear.
Here are several methods to set the validity period.

// Expire in 20 minutes
Timespan Ts = new timespan (0, 0, 20, 0 );
Response. Cookies ["mycookie"]. expires = datetime. Now. Add (TS );

// Expire one month later
Response. Cookie ["mycookie"]. expires = datetime. Now. addmouths (1 );

// Specify a specific effective date
Response. Cookies ["mycookie"]. expires = datetime. parse ("2010-10-1 ");

// Never expire
Response. Cookies ["mycookie"]. expires = datetime. maxvalue;

// Expired after the browser is closed
Response. Cookies ["mycookie"]. expires = datetime. minvalue;

9. Delete the client cookie.
To delete a client cookie, you can specify the cookie validity period in either of the following ways.
Method 1: Set the cookie validity period to a certain time in the past. For example, set the cookie validity period to the day before the current system time. The Code is as follows:
Response. Cookies ["mycookie"]. expires = datetime. Now. adddays (-1 );

Method 2: Set the cookie validity period to minvalue. When the browser is disabled, the cookies are invalid. The Code is as follows:
Response. Cookies ["mycookie"]. expires = datetime. minvalue;


10. delete a value in the multi-value cookie.
Use the remove method. The relevant code is as follows:

If (txtval1.text! = "" & Txtval2.text! = "")
{
Httpcookie Hc = request. Cookies ["Val"];
HC. Values. Remove ("val2 ");
Response. Cookies. Add (HC );
}
Else
{
Response. Write ("Enter the variable value first! ");

}

11. Use cookies to prevent repeated online voting
Cookie provides a method for storing user-specific information in Web applications. for example, when a user browses a web site for the first time, the cookie will write down the user's logon IP address. During the Cookie's validity period, when the user sends another request to browse the pages on the web site, the browser will exchange cookie information with the server to identify the user.
Create a simple program. Use the cookie feature to prevent repeated voting.
The implementation method is to save the client's IP address in the cookie object. The main code is as follows:

// Determine whether the specified IP address has been voted. If yes, a prompt dialog box is displayed.
String userip = request. userhostaddress. tostring ();
Int voteid = convert. toint32 (radiobuttonlist1.selectedindex. tostring () + 1;
// Obtain the cookie object named userip
Httpcookie oldcookie = request. Cookies ["userip"];
// Determine whether the cookie object exists
If (oldcookie = NULL)
{
Updatevote (voteid );
Response. Write ("<SCRIPT> alert ('vote successful. Thank you for your participation! ') </SCRIPT> ");
// Define a new Cookie object
Httpcookie newcookie = new httpcookie ("userip ");
Newcookie. expires = datetime. minvalue;
// Add a new Cookie variable IPaddress with the value userip
Newcookie. Values. Add ("IPaddress", userip );
// Write the variable into the cookie file
Response. appendcookie (newcookie );
Return;
}


Then, obtain the Client IP address from the cookie and determine whether the IP address has accessed the website. If yes, a prompt box is displayed, prompting the user. The main code is as follows:

// Obtain the Client IP address from the cookie
String userip = oldcookie. Values ["IPaddress"];
If (userip. Trim () = userip. Trim ())
{
Response. Write ("<SCRIPT> alert ('one IP Address can only vote once. Thank you for your participation! '); History. Go (-1); </SCRIPT> ");
Return;

}
Else
{
// Create an httpcookie object and assign it the userid name
Httpcookie newcookie = new httpcookie ("userip ");
// Assign values to the cookie subitem, that is, assign the Client IP address to the cookie subitem, and name it IPaddress
Newcookie. Values. Add ("IPaddress", userip );
// Set the expiration time for all cookies
Newcookie. expires = datetime. minvalue;
// Add the cookie to the cookies set
Response. Cookies. Add (newcookie );
// Response. appendcookie (newcookie );
Updatevote (voteid );
Response. Write ("<SCRIPT> alert ('vote successful. Thank you for your participation! ') </SCRIPT> ");
Return;
}


12. Use cookies for Automatic Login
Generally, the website provides the Automatic Logon Service. Simply put, you do not need to enter the user name or password to log on within a certain period of time after the first (or one) logon is successful.
In this example, you can log on within two weeks without entering a password.
The Code is as follows:


If (request. Cookies ["username"]! = NULL)
{
Response. Redirect ("B. aspx? Username = "+ request. Cookies [" username "]. value );
}
Else
{
If(this.txt name. Text = "A" &this.txt password. Text = "")
{
If (checkbox1.checked = true)
{
Response. Cookies ["username"]. value = system. Web. httputility. urlencode (txtname. Text );
Response. Cookies ["username"]. expires = datetime. Now. adddays (14 );
}
Response. Redirect ("B. aspx? Username = "+ system. Web. httputility. urlencode (txtname. Text ));

}
Else
{
Response. Write ("<SCRIPT> alert ('input error! ') </SCRIPT> ");
}
}



13. Use cookies for single-point Logon
Single Sign On (SSO) is one of the most popular solutions for enterprise business integration. simply put, each client can open only one website at a time. the biggest benefit is that it can relieve the pressure on the server. it is common in enterprise websites. because of the portal website, Community The more you want to open a blog, the better.
The principle of automatic logon is similar to that of Automatic Logon on November 11.

Source: http://www.aspcool.com/lanmu/browse1.asp? Id = 6964 & bbsuser = ASPnet

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.