The difference between a cookie and a session

Source: Internet
Author: User

This paper introduces and summarizes the cookie and session, and compares two knowledge points respectively, so that we have a more in-depth understanding of the cookie and session, and bring enlightenment to the flexible use of our own development work.



A. Cookie mechanism

cookies are small pieces of text that the server stores on the local machine and are sent to the same server with each request . The IETF RFC 2965 HTTP State Management mechanism is a generic cookie specification. The Web server sends cookies to the client using HTTP headers, and in the client terminal, the browser parses the cookies and saves them as a local file, which automatically binds any requests from the same server to these cookies.

Specifically, the cookie mechanism uses a scheme that maintains state on the client. It is the storage mechanism of session state on the client side, and he needs the user to open the cookie support of the clients. The purpose of cookies is to resolve the problem of stateless defects in the HTTP protocol . (an HTTP stateless protocol means that the protocol has no memory capability for transactional processing.) A lack of state means that if the previous information is required for subsequent processing, it must be re -routed , which may cause the amount of data to be transferred per connection to increase. On the other hand, it responds faster when the server does not need the previous information. )

Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser by adding a line of special instructions to the HTTP response header Follow the instructions to generate the appropriate cookie. However, purely client-side scripts such as JavaScript can also generate cookies. And the use of cookies by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies and, if a cookie declares a scope greater than or equal to the location of the resource to be requested, sends the cookie to the server on the HTTP request header of the requesting resource.

the contents of the cookie mainly include: name, value, expiration time, path and domain. The path together with the domain constitutes the scope of the cookie. If you do not set an expiration time, the cookie will be closed for the duration of the browser session. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set , the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time expires. Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them .

The session mechanism uses a solution that maintains state on the server side. At the same time, we also see that because of the server-side hold state of the scheme in the client also need to save an identity, so the session mechanism may need to use the cookie mechanism to achieve the purpose of preserving the identity. The session provides a convenient way to manage global variables.

session is for each user, the value of the variable is saved on the server, with a sessionid to distinguish which user session variable, this value is This value may also be set to be returned to the server by get when the customer disables the cookie, which is returned to the server when the user's browser is accessed.

As far as security is concerned: when you visit a site that uses a session and create a cookie on your own machine, it is recommended that the session mechanism on the server side more secure because it does not arbitrarily read the information stored by the customer.

Second, session mechanism

The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.

When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID (called the session ID.), and if it is included, it has previously created a session for this client. The server uses the session ID to retrieve it, and if the client request does not include the session ID, create a session for the client and generate a session associated with the session Id,session The value of the ID should be a string that is neither duplicated nor easily found to be patterned, and the session ID will be returned to the client in this response

Save.

This session ID can be saved by using a cookie, so that the browser can automatically play the logo to the server during the interactive process. Generally the name of this cookie is similar to Seeesionid. However, a cookie can be artificially banned, and there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned.

A technique used frequently is called URL rewriting, which attaches the session ID directly behind the URL path. There is also a technique called form-hidden fields. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted.

Both the cookie and session can be tracked, but the principle of completion is not quite the same. Under normal circumstances both can meet the demand, but sometimes can not use cookies, sometimes can not use the session. The following is a comparison of the characteristics of the two and the place of application.

Third, the difference between the cookie and session:

① different access modes (cookies can only be saved ascii,session any data type is stored)

Only ASCII strings can be stored in a cookie, and if the requirement is to access Unicode characters or binary data, the requirement is first encoded. There is no direct access to Java objects in cookies. To store slightly more complex information, it is difficult to use cookies.

In the session, you can access any type of data, including not limited to string, Integer, List, map, and so on. Session can also be directly stored in Java beans and even any Java class, objects, etc., the use of very easy. The session can be considered a Java container class.


② Different privacy policies (cookies are stored in client-side readers and sessions are stored on the server)

Cookies are stored in client-side readers and are visible to clients, and some programs on the client may snoop, copy, or modify the contents of a cookie. The session is stored on the server, is transparent to the client, and there is no risk of sensitive information disclosure.

If you choose a cookie, the best way is to try not to write sensitive information, such as your account password, to the cookie. It is best to encrypt the cookie information like Google and Baidu, submit it to the server, and then decrypt it to ensure that the information in the cookie can be read as long as I understand it. And if the choice session is more convenient, anyway, is placed on the server, the session of any privacy can be effectively protected.


③ Validity period is different (the cookie can be set for a long time, the session closes the browser expires)

Anyone who has used Google knows that Google's login information is valid for a long time if they sign in to Google. Users don't have to log back on every visit, Google

The user's login information is persisted. To achieve this effect, it is a good choice to use cookies. You only need to set the cookie expiration time property to a

A big, big number.

Since the session relies on a cookie named Jsessionid, and the cookie Jsessionid's expiration time is acquiesced to –1, simply close the reader

The session will not work, so the session can not complete the information forever effective effect. Using URL rewrite can not be done. And if you set the session

When the timeout period is too long, the server accumulates more sessions and the more likely it is to incur a memory overflow. (At this point local storage is used storage)


④ Server pressure is different (cookie pressure is less than session)

session is stored on the server side , each user will produce a session. If the number of concurrent access users is very many, there will be a lot of session,

Consumes a lot of memory. Therefore, like Google, Baidu, Sina such a high number of concurrent visits to the site, is unlikely to use the session to track customer sessions.

While the cookie is stored on the client , it does not occupy server resources. Cookies are a good choice if you have a lot of concurrent readers. About Google, Baidu

, Sina, cookies may be the only option.


⑤ storage size is different

A single cookie cannot hold more than 4K of data, and many browsers limit a maximum of 20 cookies per site.


⑤ Browser support for different

Cookies are supported by the client browser. If the client disables cookies or does not support cookies, session tracking is invalidated. On the WAP

Application, the usual cookie will not be useful.

If the client browser does not support cookies, you need to use session and URL rewrite. It is important to note that all the URLs used in the session program are

For URL rewrite, session trace will also be invalidated. For WAP applications, Session+url address rewriting may be its only option.

If the client supports cookies, the cookie can be set to both the browser window and the child window (setting the Expiration time to –1) or to everything

Valid within the Reader window (set the expiration time to an integer greater than 0). However, the session can only be valid within the Reader window and its subwindow. If two

Browser windows are irrelevant, and they will use two different sessions. (IE8 under different window sessions coherent)


⑥ differences in cross-domain support

Cookies support cross-domain access, such as setting the Domain property to ". Biaodianfu.com", and all domain names with ". biaodianfu.com" suffix can

Access the cookie. Cross-domain cookies are now commonly used in networks such as Google, Baidu, Sina, and so on. The session does not support cross-domain access

。 The session is valid only within the domain where he is located.


Iv. Summary

Only using cookies or simply using the session may not achieve the desired results. At this point, you should try to use both cookies and session. Cookies and

The use of the session will accomplish a lot of unexpected results in practical projects.

storing important information, such as login information, as a session,

additional information can be placed in a cookie if it needs to be retained


Partly transferred from:http://www.lai18.com/content/407204.html

The difference between a cookie and a session

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.