In-depth understanding of all aspects of Cookies (Basic/advanced)

Source: Internet
Author: User
Tags ssl connection

I. Preface

Cookies must be known to all, but not all are proficient. This article describes all aspects of Cookies.

Ii. Basic Knowledge

1. What is Cookies?

Cookie is a short text message that is transmitted between the Web server and the browser as user requests and pages. Cookie contains information that can be read by Web applications every time a user accesses the site.

For example, if the application sends a page to the user when the user requests the page in the site, it is not only a page, but also a Cookie containing the date and time, the user's browser obtains the Cookie while obtaining the page, and stores it in a folder on the user's hard disk.

Later, if the user requests the page on your site again, when the user enters the URL, the browser will find the Cookie associated with the URL on the local hard disk. If the Cookie exists, the browser sends the Cookie along with the page request to your site. Then, the application can determine the date and time of the user's last visit to the site. You can use this information to display a message to the user or check the expiration date.

Cookies are associated with websites rather than specific pages. Therefore, no matter which page on the site the user requests, the browser and server exchange Cookie information. When a user accesses different sites, each site may send a Cookie to the user's browser, which stores all the cookies separately.

Cookies help websites store information about visitors. In general, Cookie is a way to maintain the continuity of Web applications (that is, execution status management. Except for a short period of actual information exchange time, the browser and the Web server are disconnected. The Web server processes each request sent to the Web server separately. However, in many cases, it is very useful for Web servers to identify users on user request pages. For example, a Web server on a shopping site tracks each shopper so that the site can manage the shopping cart and other user-specific information. Therefore, Cookie can be used as a business card to provide relevant identification information to help the application determine how to continue execution.

Cookie can be used for multiple purposes, all of which are to help websites remember users. For example, a site that implements a public opinion test can simply use cookies as a Boolean value to indicate whether the user's browser has participated in the vote, so that the user cannot perform a second vote. Websites requiring users to log on can use cookies to record that users have logged on, so that users do not have to enter creden。 every time.

2. How to store Cookies

Cookies are stored on your local machine. Different browsers are stored in different folders and saved by domain name. That is, Cookies between websites are not covered by each other.

Users of IE can find the txt files of Cookies in local documents. windows server 2003/xp stores the files in different operating systems:

C: \ Documents ents and Settings \ Administrator \ Cookies folder.

The name txt is saved by domain name. For example, the cookies in the localhost domain are:

Administrator@localhost1_12.16.txt or administrator@localhost1_22.16.txt

The [1] and [2] following change with each save.

3. How to transmit Cookies

Cookies are transmitted between the Web server and the browser. Save it in the Http request.

(1) Request page

In the Http header of a pageLocal CookiesIn the Http header, note the following bold parts:

Copy codeThe Code is as follows: GET/Cookies/Test. aspx HTTP/1.1
Host: localhost: 1335
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv: Gecko/20090715 Firefox/3.5.1 GTB5 (. net clr 3.5.30729)
Accept: text/html, application/xhtml + xml, application/xml; q = 0.9, */*; q = 0.8
Accept-Language: zh-cn, zh; q = 0.5
Accept-Encoding: gzip, deflate
Accept-Charset: GB2312, UTF-8; q = 0.7, *; q = 0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: My. Common. TestCookieInfo = Pkid = 999 & TestValue = aaabbbcccdddeee

(2) page response

If the page requires writing Cookies, the returned Http is as follows. Note the bold Section:

Copy codeThe Code is as follows: HTTP/1.x 200 OK
Server: ASP. NET Development Server/
Date: Thu, 06 Aug 2009 03:40:59 GMT
X-AspNet-Version: 2.0.50727
Set-Cookie: My. Common. TestCookieInfo = Pkid = 999 & TestValue = aaabbbcccdddeee; expires = Fri, 07-Aug-2009 03:40:59 GMT; path =/
Cache-Control: private
Content-Type: text/html; charset = UTF-8
Content-Length: 558
Connection: Close

4. How to view Cookies

(1) view txt files of Cookies

IE users can directly view the txt files of Cookies.
For example, C: \ Documents ents and Settings \ Administrator \ Cookies \ administrator@localhost1_12.16.txt

(2) Use plug-ins

FF, you can use the Web Developer plug-in to conveniently view, delete, and modify Cookies:


View page Cookies:

3. Cookies high-level knowledge

1. Cookie restrictions

Most browsers support a Cookie of up to 4096 bytes.

The browser also limits the number of cookies that the site can store on the user's computer. Most browsers only allow 20 cookies to be stored on each site;Note that the 20 values here refer to the primary key value, that is, 20 Cookies. However, each cookie record can contain several subkeys, which will be explained in detail below. If you try to store more cookies, the oldest Cookie will be discarded.Some browsers impose absolute limits on the total number of cookies they will accept from all sites, typically 300.

2. Storage Format of Cookies

Cookies can contain a primary key, which then contains a subkey. For example, the format for obtaining Cookies in is:

Copy codeThe Code is as follows: Request. Cookies [key] [subkey]. ToString ();

The key is the primary key, and the subkey is the subkey associated with the primary key.

(1) local disk storage format:

Copy codeThe Code is as follows: My. Common. TestCookieInfo
Pkid = 999 & TestValue = aaabbbcccdddeee

Pkid = 999 & TestValue = aaabbbcccdddeee is the value of Cookies. Because the format of subkey = subvalue is used, this cookie contains subkeys.

(2) Cookie format in Javascript

The Cookie in Javascript is a string obtained through document. cookies. The character format is as follows:

My. Common. SubKey= Pkid = 999 & TestValue = aaabbbcccdddeee;SingleKey= SingleKeyValue

The preceding string contains two Cookies. One is the SingleKey that does not contain the subkey, and the other is the My that contains the pkid and TextValue subkeys. common. subKey. The two cookies are separated.

(3) Cookies in Asp. Net

Like all server languages, Asp. Net uses the set class to save Cookies:

Copy codeThe Code is as follows: public sealed class HttpCookieCollection: NameObjectCollectionBase

Through the Cookies of HttpResquest and HttpResponse objects, you can obtain and write Cookies on the current page.

3. content encoding format of Cookies

The cookie value isYou can save punctuation marks other.However, Chinese characters cannot be saved. Garbled characters appear when saving Chinese characters.

Therefore, Cookies must be encoded and decoded in a unified manner. To enable decoding and encoding on both the browser and server, the UTF Encoding format must be used in a unified manner.

This is mainly because only UTF Encoding formats can be used in javascript.

4. Path attribute of Cookies

The Path attribute of Cookies indicates the Path in which the current Cookies can be used.

For example, the following two Cookies with the same name:

Two Cookies with the same name but different paths are allowed.

The Cookies in the path on this page are obtained first on the server or client.

That is to say, if you get the cookie value testKey on the page under/chapter10/path, you can only get the value testValue222222.

5. Cookie expiration time

If no expiration time is set when Cookies are saved, the expiration time of Cookies is "the current browser process is valid", that is, when the browser is closed like Session, it disappears.In, you can set the expiration time of the HttpCookie object to DateTime. MinValue to specify that the cookie takes effect with the browser. (This sentence is hard to come by. I found it with the help of my head and other people .)

If the expiration time is set and later than the current time, the cookie value is saved.

If the expiration time is set but less than or equal to the current time, the Cookies are cleared.

6. Cookies and sessions

Sometimes we ignore the relationship between Cookies and sessions. However, they are inseparable.

The unique identifier of a Session: SessionID is usually stored in Cookies (or saved in URLs ). For Asp. Net, SessionID is stored in Cookies with the key value "ASP. NET_SessionId,

Because the number of Cookies stored is limited, our system must pay attention to prevent this key cookie from being washed away when saving Cookies. The best practices described below-the Cookies are specially processed in codes that store Cookies with strong objects.

7. Cookies Encryption

When setting Cookies, there is an option Secure to control the encryption feature of Cookies.

If the Cookie is transmitted through an SSL connection (HTTPS), the value is true; otherwise, the value is false. The default value is false.

If we save a cookie and set encryption, the cookie cannot be obtained on non-HTTPS pages, whether in javascript or on the server side. However, the existence of this cookie can still be seen locally.

8. Cookies and Ajax

If Ajax requests access a server page, the server page can write Cookies and sessions to the user's browser.

Iv. Cookies Best Practices

After learning about Cookies, the following describes the best event methods. It consists of two parts: client and server.

(1) Saving Cookies in Asp. Net

Generally, we use Request and Response objects to directly operate on Cookies:

Write Cookies:

Copy codeThe Code is as follows: Response. Cookies ["k1"]. Value = "k1Value ";
Response. Cookies ["k2"] ["k2-1"] = "k2-1Value ";
Response. Cookies. Add (new HttpCookie ("k3", "k3Value "));

Read Cookies:
Copy codeThe Code is as follows: Request ["k1"];
Request. Cookies ["k1"]. Value;
Request. Cookies ["k2"] ["k2-1"];
Request. Cookies. Get (0). Value;

Note that Request ["k1"] is a familiar method for obtaining get and post parameters, and can also obtain Cookies!

In addition, some of the statements above must be accessed through the Value attribute, while others do not.

(2) Saving Cookies as objects

The following provides a tool class for saving Cookies as an object. Only one cookie is used, and all attributes are stored on the subkey.

Source code:

Copy codeThe Code is as follows: // <summary>
/// Cookies base class. This class is derived from the data classes that need to save Cookies. You can save and read strongly-typed objects in Cookies.
/// </Summary>
/// <Remarks>
/// 2009.8.6 ziqiu. zhang created
/// </Remarks>
/// <Example>
/// Assume that MyCookiesInfo obtains the object from Cookies:
/// <Code>
/// CookieInfo item = new CookieInfo (); // the object has been constructed from Cookies in the future.
/// </Code>
/// Save the object in Cookies:
/// <Code>
/// CookieInfo item = new CookieInfo ();
/// Item. value = "test value ";
/// Item. SetCookies ("1"); // Cookies are valid for one day
/// </Code>
/// </Example>
[System. Serializable]
Public class CookieInfo
# Region ================================ Constructed Method ====================== ====
/// <Summary>
/// Constructor
/// </Summary>
Public CookieInfo ()
# Endregion
# Region = Public Method = ====
/// <Summary>
/// Obtain the expiration time of the Current cookie
/// </Summary>
/// <Returns> expiration time </returns>
Public DateTime GetExpiresTime ()
String cookieName = GetType (). ToString ();
If (HttpContext. Current. Request. Cookies [cookieName]! = Null)
Return HttpContext. Current. Request. Cookies [cookieName]. Expires;
Return DateTime. MinValue;
/// <Summary>
/// Save Cookies. The expiration time is disabled by the browser.
/// </Summary>
/// <Param name = "expiresTime"> cookie expiration event </param>
/// <Returns> whether the storage is successful </returns>
Public bool Save ()
Return this. Save (DateTime. MinValue );
/// <Summary>
/// To save Cookies, you must specify the expiration time.
/// </Summary>
/// <Param name = "expiresTime"> cookie expiration event </param>
/// <Returns> whether the storage is successful </returns>
Public bool Save (DateTime expiresTime)
String CookieName = GetType (). ToString ();
HttpCookie SessionCookie = null;
// Backup SessionId.
If (HttpContext. Current. Request. Cookies ["ASP. NET_SessionId"]! = Null)
String SesssionId = HttpContext. Current. Request. Cookies ["ASP. NET_SessionId"]. Value. ToString ();
SessionCookie = new HttpCookie ("ASP. NET_SessionId ");
SessionCookie. Value = SesssionId;
// Set the cookie expiration time.
DateTime dtExpiry = expiresTime;
HttpContext. Current. Response. Cookies [CookieName]. Expires = dtExpiry;
// Set the cookie domain name.
String domain = string. Empty;
If (HttpContext. Current. Request. Params ["HTTP_HOST"]! = Null)
// Domain = " ";
Domain = HttpContext. Current. Request. Params ["HTTP_HOST"]. ToString ();
// If the domain name is or a multi-level domain name, it must be converted to
If (domain. IndexOf (".")>-1)
String [] temp = domain. Split ('.');
If (temp. Length> = 3)
Domain = temp [temp. Length-2]. Trim () + "." + temp [temp. Length-1]. Trim ();
HttpContext. Current. Response. Cookies [CookieName]. Domain = domain;
// Write the attributes of the class into the Cookie.
PropertyInfo [] Propertys = GetType (). GetProperties ();
Foreach (PropertyInfo pi in Propertys)
Object oj = pi. GetValue (this, null );
Type type = pi. PropertyType;
String valueStr = string. Empty;
If (oj! = Null & oj. ToString ()! = String. Empty)
If (type = Type. GetType ("System. DateTime "))
ValueStr = (DateTime) oj). ToString ("yyyy/MM/dd HH: mm: ss", System. Globalization. DateTimeFormatInfo. InvariantInfo );
ValueStr = oj. ToString ();
HttpContext. Current. Response. Cookies [CookieName] [pi. Name] = HttpUtility. UrlEncode (valueStr );
// If the total number of cookies exceeds 20, rewrite ASP. NET_SessionId to prevent Session loss.
If (HttpContext. Current. Request. Cookies. Count> 20 & SessionCookie! = Null)
If (SessionCookie. Value! = String. Empty)
HttpContext. Current. Response. Cookies. Remove ("ASP. NET_SessionId ");
HttpContext. Current. Response. Cookies. Add (SessionCookie );
Return true;
/// <Summary>
/// Retrieve the Cookie value
/// </Summary>
Public void Load ()
String cookieValue = string. Empty;
String CookieName = GetType (). ToString ();
// Retrieve the value from the cookie by traversing the attribute and write it back to the attribute.
PropertyInfo [] Propertys = GetType (). GetProperties ();
Foreach (PropertyInfo pi in Propertys)
CookieValue = HttpUtility. UrlDecode (HttpContext. Current. Request. Cookies [CookieName] [pi. Name]. ToString ());
CookieValue = string. Empty;
If (pi. CanWrite & cookieValue! = Null & cookieValue! = String. Empty)
Object obb = cookieValue;
Type type = pi. PropertyType;
Obb = Convert. ChangeType (obb, type );
Pi. SetValue (this, obb, null );
Catch {}
# Endregion


First, describe how to use this class.

Create a model for the classes that you want to store in Cookies and inherit from CookieInfo. For example, the MyCookieInfo class is created below, which includes the attributes pkid, TestValue, and TestDateTime:

Copy codeThe Code is as follows: // <summary>
/// Data object for storing Cookies
/// </Summary>
[System. Serializable]
Public class MyCookieInfo: CookieInfo
Private int m_Pkid = 0;
Public int Pkid
Return m_Pkid;
M_Pkid = value;

Private string m_TestValue = "";
Public string TestValue
Return m_TestValue;
M_TestValue = value;

Private DateTime m_TestDateTime = DateTime. Now;
Public DateTime TestDateTime
Return m_TestDateTime;
M_TestDateTime = value;

Next, you can use the Save and Load methods of the object to Save and read Cookies:Copy codeThe Code is as follows: • Save
The Save method has two reloads. The Save method without parameters indicates that the cookie expires at the same time as the browser, that is, when the browser is closed, the cookie disappears. Otherwise, the cookie expiration time is required.
MyCookieInfo testCookies = new MyCookieInfo ();
TestCookies. Pkid = 1;
TestCookies. TestValue = "Chinese test ";
TestCookies. Save (); • Read

MyCookieInfo testCookies = new MyCookieInfo ();
TestCookies. Load ();
This. lblMsg. Text = "Pkid:" + testCookies. Pkid. ToString ();
This. lblMsg. Text + = ", TestValue:" + testCookies. TestValue. ToString ();
This. lblMsg. text + = ", TestDateTime:" + testCookies. testDateTime. toString ("yyyy/MM/dd HH: mm: ss", System. globalization. dateTimeFormatInfo. invariantInfo );

Now we can read and save Cookies for a strongly typed object.
(3) use Javascript to operate Cookies

We also need to operate Cookies on the client.

The following are the jQuery tool functions specially used to operate Cookies.
Of course, this tool function can be changed to a standard Javascript function with a slight modification.

Tool function description:

Method Signature: jQuery. cookie (name, subName, value, options)

Instructions: read, write, and delete Cookies

Method parameters:

Name Description Example
Name Primary Key Value of cookies Read primary key:
$. Cookie ("singleKey ")

Write cookies. The value is a string:
$. Cookie ("singleKey", "", "singleKey-value", {expires: 1, path: "/", secure: false })

SubName The subkey name. When writing data, pass null or null. Read subkeys:
$. Cookie ("multiKey", "subName1 ")

Write cookies. The value is an object:
Var subNameObj = {subName1: "aaa", subName2: "bbb", subName3: "ccc"}; $. cookie ("multiKey", "", subNameObj, {expires: 1, path: "/", secure: false });

Value Cookie value, which can be a string or object.
If it is an object, each attribute of the object is saved in the cookie subkey.
See the instance above.
Options Parameters:
Expires: it can be a numeric or Data type object.
If a number is input, it indicates that it expires several days later.
Path: path. The default value is the domain name root directory ("/").
Secure: whether to enable encryption. The default value is no.

Specify the expiration time:

Var myDate = new Date (); myDate. setFullYear (2009, 10, 10); $. cookie ("singleKey", "", "singleKey-value", {expires: myDate, secure: false })

1 day after expiration:

Var time = Date (); $. cookie ("singleKey", "", "singleKey-value", {expires: 1, path: "/", secure: false })

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: 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.