Cookie programming in C # And cookie in Javascript

Source: Internet
Author: User

Cookies are called "cookies". They first appeared in Netscape Navigator 2.0. Cookies are actually files created by Web servers that store information on computers. So why does the Web server need to create such a file on the client? This is because when a client sends a request to the Web server (for example, when you are preparing to browse the page), the server treats the client as the first time whether it is the first visit, the Web server simply responds and closes the connection to the user. The shortcomings brought about by this process are obvious. Since Netscape developed a cookie, it can be used to store user identification information. The role of cookie can record the pages you have visited on the site, so that you can customize the viewing when you visit the site next time. Cookies can also store personal identifiable information. Personal identifiable information can be used to identify or contact you, such as name, email address, home or work address, or phone number. However, the website can only access the personal identifiable information you provide. For example, the website cannot determine your email name unless you provide an email name. In addition, the website cannot use cookies to access other information on the computer. Unless you provide. So where is the cookie stored? If Windows 98 is installed on the "c" drive, the cookies are stored in the "C:/Windows/cookies" directory; if Windows 2000 is installed on the "c" drive, the cookies are stored in the "C:/Documents and Settings/Administrator/cookies" directory. After learning so much about cookies, let's take a look at the focus of this article-How C # program cookies. The main content is as follows: C # is how to write cookies, and C # is how to access the cookies written by itself.

I. The software environment for program design and operation described in this article:

Microsoft Windows 2000 Server Edition
. NET Framework SDK beta 2

C # cookie programming is implemented through ASP. NET pages.

II. C # How to Write cookies:

To write a cookie, follow these steps:

Create an httpcookie object to construct a cookie. The object name is the cookie name generated later. The Code is as follows:
Httpcookie = new httpcookie ("user-defined cookie name ");

Then, assign a string value to the "value" attribute of the created httpcookie object. The "value" value is the value of the cookie generated later. The Code is as follows:
Cookie. value = "the user assigns a value to the cookie"; if the cookie value you want to write is not a simple string, but a complex data type, we know that these data types cannot be directly stored in cookies, because they can only store strings. However, you can use a work und to convert the complex data type into multiple strings, and assign these strings to the generated cookie values at the same time, in this way, the content in cookies is enriched, and the functions completed by using cookies are also powerful in the future. In this case, you may wonder when you have browsed the Web server and waited for too long. Because the information has been stored in the cookie generated by the Web server when you first browsed the page. The following code stores multiple strings into cookies:
Cookie ["name"] = "Wang Tian ";
Cookie ["gender"] = "male ";
Cookie ["Age"] = "26 ";

Cookies are temporary and permanent. Permanent cookies are stored on the computer as files, and are retained on the computer when Internet Explorer is disabled. When you access the site again, the website that creates the cookie can read it. During specific programming, the lifecycle of the cookie is set when the cookie is written. The specific code is as follows:
Datetime dtnow = datetime. now;
Timespan tsminute = new timespan (0, 1, 0, 0 );
Cookie. expires = dtnow + tsminute;

The above Code sets the life cycle of the generated cookie to "One Hour". You can modify the "timespan" attribute to set the specific life cycle of the generated cookie.
Finally, call the "add ()" method of the "response. Cookies" object to add this object, so that a cookie can be generated. The Code is as follows:
Response. Cookies. Add (cookie );
The following code is the complete code (write. aspx) for writing cookies in C ):
<% @ Language = "C #" %>
<SCRIPT runat = "server">
Void writeclicked (Object sender, eventargs E)
{
// Create an httpcookie object
Httpcookie cookie = new httpcookie (namefield. Text );
// Set this cookie value
Cookie. value = valuefield. text;
// Set the cookie lifecycle, which is defined as an hour
Datetime dtnow = datetime. now;
Timespan tsminute = new timespan (0, 1, 0, 0 );
Cookie. expires = dtnow + tsminute;
Cookie ["name"] = "Wang Tian ";
Cookie ["gender"] = "male ";
Cookie ["Age"] = "26 ";
// Add this cookie
Response. Cookies. Add (cookie );
Response. Write (namefield. Text + "Cookie created <br> <HR> ");
}
</SCRIPT>
<HTML>
<Body>
<H3> Create a cookie on the C # page The cookie lifecycle is defined as one hour.
<Form runat = "server">
Cookie name: <asp: textbox id = "namefield" runat = "server"/> <br>
Cookie value: <asp: textbox id = "valuefield" runat = "server"/> <br>
<Asp: button text = "create cookie" onclick = "writeclicked" runat = "server"/> <br>
</Form>
</Body>
</Html>

Is the interface after the code is run:

Figure 01: C # program running interface for writing cookies

Of course, the cookie generated by the above Code is a bit monotonous on the content. In fact, for cookies with rich content, there are many other attributes that can be used to make full use of these attributes. The following table lists common attributes of cookies:

Attribute description
Domain: Set/obtain the domain name to which the cookie belongs. Once this attribute is set, only the Web server of this domain name can access this cookie. It can be set to "ccw.com.cn"
Path: Specifies the path to which the cookie belongs. If so, the Web Page Accessing the cookie is restricted to this path. Web pages in other paths cannot be accessed.
Secure sets/gets an identifier to indicate whether the cookie can be securely transmitted to the client browser using the HTTP protocol.
Haskeys indicates whether the cookie is composed of multiple strings.

When writing cookies, it is very important to use these attributes to the maximum extent possible.

3. C # How to read generated cookies:

Reading a specified cookie is much easier than writing a cookie. You only need to use the "request. Cookies" object. The following method reads the specified cookie Name:

Httpcookie cookie = request. Cookies ["Cookie name"];

The following figure shows the number of cookies that have been read:

Response. write (cookie. value. tostring (); master the above key points, it is very easy to read the cookie, the following is the program code to read the cookie (read. aspx): <% @ Language = "C #" %>
<SCRIPT runat = "server">
Void readclicked (Object sender, eventargs E)
{
// Obtain the cookie name entered by the user
String strcookiename = namefield. text;
// Obtain the cookie
Httpcookie cookie = request. Cookies [strcookiename];
// Determine whether the cookie entered by the user exists
If (null = cookie ){
Response. Write ("no specified Cookie found <br> <HR> ");
}
Else {
// Find the specified cookie and display the cookie value
String strcookievalue = cookie. value. tostring ();
Response. Write (strcookiename + "cookie value: <B>"
+ Strcookievalue + "</B> <br> <HR> ");
}
}
</SCRIPT>
<HTML>
<Body>
Read the specified cookie value on the C # page. <br>
<Form runat = "server">
Enter the name of the cookie to read:
<Asp: button text = "read cookie" onclick = "readclicked" runat = "server"/>
</Form>
</Body>
</Html>

Is the interface after the code is run:

Figure 02: program running interface for reading the value of a specified cookie

Iv. Summary:

So far, we have introduced most of the content for Cookie programming using C. In fact, cookies play a major role in the Internet. For example, it allows a Web site to track the access times of a specific visitor, the last access time, and the path of the visitor to the site. It can also tell online advertisers the number of clicks on an advertisement, in this way, users can more accurately deliver advertisements. It allows users to access some websites they have browsed without entering their passwords and usernames; the most important thing is that it can help the site collect user data for personalized services. After mastering C #'s cookie programming, you can make full use of cookies in the program to implement these functions. Do not believe it.

 

 

Cookie in Javascript

 

  1. <SCRIPT>
  2. // Author of the cookie writing function: Yan zhenkai
  3. Function setcookie (name, value) // two parameters: one is the name of the cookie and the other is the value.
  4. {
  5. VaR days = 30; // This cookie will be saved for 30 days
  6. VaR exp = new date (); // new date ("December 31,999 8 ");
  7. Exp. settime (exp. gettime () + days x 24x60*60*1000 );
  8. Document. Cookie = Name + "=" + escape (value) + "; expires =" + exp. togmtstring ();
  9. }
  10. Function getcookie (name) // The cookie function.
  11. {
  12. VaR arr = Document. Cookie. Match (New Regexp ("(^ |)" + name + "= ([^;] *) (; | $ )"));
  13. If (Arr! = NULL) return Unescape (ARR [2]); return NULL;
  14. }
  15. Function delcookie (name) // delete a cookie
  16. {
  17. VaR exp = new date ();
  18. Exp. settime (exp. gettime ()-1 );
  19. VaR cval = getcookie (name );
  20. If (cval! = NULL) document. Cookie = Name + "=" + cval + "; expires =" + exp. togmtstring ();
  21. }
  22. Setcookie ("Xiaoqi", "3 ")
  23. Alert (getcookie ('xiaoqi '));
  24. </SCRIPT>

A very practical JavaScript function for reading and writing cookies

A very practical JavaScript function for reading and writing cookies

 

  1. Function getcookieval (offset)
  2. // Obtain the decoded cookie value
  3. {
  4. VaR endstr = documents. Cookie. indexof (";", offset );
  5. If (endstr =-1)
  6. Endstr = documents. Cookie. length;
  7. Return Unescape (events. Cookie. substring (offset, endstr ));
  8. }
  9. Function setcookie (name, value)
  10. // Set the cookie value
  11. {
  12. VaR expdate = new date ();
  13. VaR argv = setcookie. arguments;
  14. VaR argc = setcookie. Arguments. length;
  15. VaR expires = (argc> 2 )? Argv [2]: NULL;
  16. VaR Path = (argc> 3 )? Argv [3]: NULL;
  17. VaR domain = (argc> 4 )? Argv [4]: NULL;
  18. VaR secure = (argc> 5 )? Argv [5]: false;
  19. If (expires! = NULL) expdate. settime (expdate. gettime () + (expires * 1000 ));
  20. Events. Cookie = Name + "=" + escape (value) + (expires = NULL )? "": ("; Expires =" + expdate. togmtstring ()))
  21. + (Path = NULL )? "": ("; Path =" + path) + (domain = NULL )? "": ("; Domain =" + domain ))
  22. + (Secure = true )? "; Secure ":"");
  23. }
  24. Function delcookie (name)
  25. // Delete the cookie
  26. {
  27. VaR exp = new date ();
  28. Exp. settime (exp. gettime ()-1 );
  29. VaR cval = getcookie (name );
  30. Documents. Cookie = Name + "=" + cval + "; expires =" + exp. togmtstring ();
  31. }
  32. Function getcookie (name)
  33. // Obtain the original cookie value
  34. {
  35. VaR Arg = Name + "= ";
  36. VaR Alen = Arg. length;
  37. VaR clen = documents. Cookie. length;
  38. VaR I = 0;
  39. While (I <clen)
  40. {
  41. VaR J = I + Alen;
  42. If (documents. Cookie. substring (I, j) = Arg)
  43. Return getcookieval (j );
  44. I = documents. Cookie. indexof ("", I) + 1;
  45. If (I = 0) break;
  46. }
  47. Return NULL;
  48. }

 

 

  1. <Script language = "JavaScript">
  2. <! --
  3. Function openpopup (){
  4. Url = "popup.htm"
  5. Window. Open ("gonggao.htm", "gonggao", "width = 260, Height = 212, Left = 200, Top = 0 ")
  6. }
  7. Function get_cookie (name ){
  8. VaR search = Name + "="
  9. VaR returnvalue = "";
  10. If (events. Cookie. length> 0 ){
  11. Offset = documents. Cookie. indexof (Search)
  12. If (offset! =-1 ){
  13. Offset + = search. Length
  14. End = documents. Cookie. indexof (";", offset );
  15. If (END =-1)
  16. End = documents. Cookie. length;
  17. Returnvalue = Unescape (events. Cookie. substring (offset, end ))
  18. }
  19. }
  20. Return returnvalue;
  21. }
  22. Function helpor_net (){
  23. If (get_cookie ('popped') = ''){
  24. Openpopup ()
  25. Documents. Cookie = "popped = yes"
  26. }
  27. }
  28. Helpor_net ()
  29. // -->
  30. </SCRIPT>

If you click OK, as long as the cookie is unclear, the system will not prompt for future access. If you do not click OK, the system will prompt every time. Put it in the JS file, full site inclusion

  1. <Script language = "JavaScript">
  2. <! --
  3. VaR the_cookie = Document. Cookie;
  4. VaR broken_cookie = the_cookie.split (":");
  5. VaR the_visiteraccepted = Unescape (broken_cookie [1]);
  6. //
  7. If (the_visiteraccepted = "undefined "){
  8. VaR TMP = confirm ('when and where are Chinese people. ');
  9. If (TMP = false ){
  10. Window. Close ();
  11. } Else {
  12. VaR the_visiteraccepted = 1;
  13. VaR the_cookie = "ilovechina = visiteraccepted:" + escape (the_visiteraccepted );
  14. Document. Cookie = the_cookie;
  15. }
  16. }
  17. // -->
  18. </SCRIPT>

1. Cookie compatibility

The cookie format has two different versions. The first version, called Cookie version 0, was originally developed by Netscape and is supported by almost all browsers. The newer version, Cookie version 1, is developed according to RFC 2109. To ensure compatibility, Java stipulates that all the cookie-related operations mentioned earlier are performed on old versions of cookies. The new Cookie version is not supported by the javax. servlet. http. Cookie package.

2. Cookie content

The character restrictions of the same cookie content vary with different cookie versions. In cookie version 0, some special characters, such as space, square brackets, Parentheses, equal signs (=), commas, double quotation marks, slashes, question marks, @ symbols, colons, the semicolon cannot be used as the cookie content.

 

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.