Differences and connections between cookies and sessions

Source: Internet
Author: User
Tags server memory

Differences between cookie and session

I have seen a detailed explanation of the session on the Internet. It feels good that many people have been confused with the cookie and session. Therefore, I have borrowed some previous summaries here, I have modified and improved my understanding and added the differences and connections between the two. If there are any mistakes, please criticize and correct them.

I,SessionConcept

Session: A session refers to a series of actions/messages that start and end up. For example, a session can be called during a call from the process of dialing the phone to the process of hanging up the phone. Here session refers to the whole process from opening a browser to accessing a Web site to closing access to this web site.

II,HTTPProtocol and status persistence

The HTTP protocol itself is stateless, which is consistent with the original purpose of the HTTP protocol. The client simply needs to request the server to download some files, no client or server needs to record the previous behavior of each other, and each request is independent.

Cookie is used to solve the stateless defects of HTTP. As for the later session mechanism, it is another solution that maintains the status between the client and the server.

Let's use several examples to describe the difference and connection between the cookie and session mechanism.

For example, a coffee shop has a promotion activity: a free cup of coffee is offered for five coffee cups. However, a customer generally cannot consume five coffee cups at a time. In this case, it is necessary to record the consumption quantity of a customer in some way. Therefore, there are several solutions: 1. The shop clerk is very powerful and can remember the consumption quantity of each customer. As long as the customer enters the coffee shop, the shop clerk will know how to deal with it. This method is supported by the Protocol itself.

2. Send a card to the customer, which records the consumption quantity and generally has a validity period. For each consumption, if the customer shows this card, the current consumption will be associated with the previous or later consumption. In this way

The cookie mechanism.

3. Send a membership card to the customer. No information except the card number is recorded. If the customer shows the card at each purchase, then the clerk finds the log corresponding to this card number in the store's record to add some consumption information. In this way

The session mechanism is maintained on the server side.

Because the HTTP protocol is stateless and does not need to be stateful for various reasons, the next two solutions have become a realistic choice. Specifically, the cookie mechanism adopts the client-side persistence scheme, while the session mechanism adopts the server-side persistence scheme. At the same time, we can also see that because the server-side persistence scheme also needs to save an identifier on the client, the session mechanism may need to use the COOKIE Mechanism to save the identifier, but in fact it has other options.

III,Understanding COOKIE Mechanism

The basic principle of the cookie mechanism is the same as in the above example, but there are still several problems to solve: how to distribute "membership cards", the content of "membership cards", and how customers use "membership cards ".

Cookie distribution mechanism:

The orthodox cookie distribution is implemented by extending the HTTP protocol. The server prompts the browser to generate the corresponding cookie by adding a special line in the HTTP response header. And stored in Temporary Internet Files. However, pure client scripts such as JavaScript or VBScript can also generate cookies. Cookies are automatically sent to the server in the background by the browser according to certain principles. The browser checks all stored cookies. If a cookie declares the scope of action (composed of the path and domain in the cookie) the cookie is attached to the HTTP request header of the requested resource and sent to the server. This means that the McDonald's membership card can only be presented in the McDonald's store. If a branch still has its own membership card, in addition to the McDonald's membership card, the store's membership card is also presented.

Cookie content:

Cookie content mainly includes: name, value, expiration time, path and domain.

1. Domain: You can specify a domain such as .google.com or a specific machine in a domain such as www.google.com or froogle.google.com.

2. Path: the URL path following the domain name, such as // or/Foo.

The combination of paths and domains constitutes the scope of cookie.

If no expiration time is set, it indicates that the life cycle of the cookie is the browser session, because it is only stored in the client memory, and the cookie disappears as long as the browser window is closed. This cookie is called a session cookie. Session cookies are generally stored in the memory instead of on the hard disk. Of course, this behavior is not standardized. If the expiration time is set, the browser will save the cookie to the hard disk, and then open the browser again. These cookies are still valid until the preset expiration time is exceeded. Cookies stored on hard disks can be shared among different browser processes, such as two IE Windows. For Cookies stored in the memory, different browsers have different processing methods. For IE, a window opened by pressing CTRL + N (or from the File menu) or another IE kernel browser (such as 360 or sogou) can be shared with the original window, other new ie processes cannot share the memory cookies of opened windows. for Mozilla firefox8.0, all processes and tabs can share the same cookies.

Generally, the window opened with window. Open in Javascript will share the memory cookie with the original window. Browser does not recognize session cookies. This method often causes a lot of trouble for Web application developers who adopt the session mechanism.

The following is an example of how goolge sets the cookie response header.

HTTP/1.1 302 found

Location: http://www.google.com/intl/zh-CN/

Set-COOKIE: Pref = id = 0565f77e132de138: nw = 1: TM = 1098082649: LM = 1098082649: S = kaeacfpo49ria_d8; expires = Sun, 17-Jan-2038 19:14:07 GMT; path =/; domain = .google.com

Content-Type: text/html

The cookie is automatically sent when the browser accesses goolge resources again.

IV,Understanding session mechanism

The session mechanism is a server-side mechanism. The server uses a structure similar to a hash to save information.

When the program needs to create a session for a client request, the server first checks whether the client request contains a session ID, called the session ID, if a session ID is included, it indicates that a session has been created for this client before, and the server uses the session ID to retrieve the session (if not, A new session may be created in the server memory). If the client request does not contain the session ID, the client creates a session and generates a session ID associated with the session, the value of the session ID should be a string that is neither duplicated nor easily found to be counterfeited. The session ID will be returned to the client for saving in this server response. The method for saving the session ID is generally to create a cookie in the client browser and save the session ID in the cookie, in this way, the browser can automatically send this identifier to the server according to the Rules during the interaction process.

Generally, the cookie name is similar to seeesionid. For example, for the cookie generated by Weblogic for Web applications, JSESSIONID = byok3vjfd75apnrf7c2hmdnv6nlerjq99zwpbng! -145788764, whose name is JSESSIONID.

Because cookies can be artificially disabled, there must be other mechanisms so that session IDs can still be passed back to the server when cookies are disabled. A frequently used technology called URL rewriting is to directly append the session ID to the end of the URL path. There are two additional methods, one is as the additional information of the URL path, the format is http ://..... /xxx; JSESSIONID = byok3vjfd75apnrf7c2hmdnv6qzcyzwpbng! -145788764,

The other is appended to the URL as a query string (querystring method), in the form of http: //.../XXX? JSESSIONID = byok3vjfd75apnrf7c2hibyenlerjq99zwpbng! -145788764 there is no difference between the two methods for users, but they are handled differently by the server during parsing, the first method also helps to distinguish the session ID information from the normal program parameters.

To maintain the status throughout the interaction process, the session ID must be included after the path that each client may request.

Another technique is form hidden fields. The server automatically modifies the form and adds a hidden field so that the session ID can be passed back to the server when the form is submitted.

Currently, this technology is rarely used. In fact, this technology can be simply replaced by rewriting the URL of the action application.

When talking about the session mechanism, we often hear the misunderstanding that "the session disappears as long as the browser is closed ". This statement is incorrect. For a session, the server keeps the session in the memory unless the program notifies the server to delete a session, generally, a program sends a command to delete a session when the user logs off. For example, the program exits safely on an online bank, however, the browser will never notify the server that it is about to close before it closes, so the server will not have the opportunity to know that the browser has been closed, most session mechanisms use session cookies to store session IDs. Because the session cookie is deleted from the memory after the browser is closed, the session ID disappears, when the server is connected again, the original session cannot be found. If the cookie set by the server is saved to the hard disk, or the HTTP request header sent by the browser is rewritten by some means, the original session ID is sent to the server, then you can still find the original session when you open the browser again.

It is precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the session. The default value is generally 30 minutes, when the last time the session is used exceeds the expiration time, that is, when the interval between the two sessions exceeds the expiration time, the server can think that the client has stopped the activity, the server deletes the session from the memory to save storage space.

V,

CookieAndSessionDifferences and connections

 


Differences

Cookie

Session

Storage location

Client

Server

Sharing

Shared by multiple browsers

Exclusive to only one browser

Storage Format

Session cookies are stored in the client memory.

If the cookie expiration time is set, it is stored in the Temporary Internet file of the client browser and saved on the hard disk.

Only stored in the server memory

Storage content and type

The cookie only stores the specified content (the path field of the name value expiration time) and is only a string type.

The session can store any content, with unlimited types. It can be a class object and a set.

Whether non-English letters are supported

Non-English is not directly supported. encoding and decoding are required.

Directly supports non-English

Encryption

Encrypted

Encryption not required

Unit of lifecycle time

Seconds

Minute

Lifecycle modification method

Modify in a web application, such as the setmaxage () method.

1. modify the configuration file of the server software. The default value is 30 minutes. Modify the session lifecycle of the entire site.

2. In the project's web application, modify only the session lifecycle of the Web application.

3. Modify only the specified session lifecycle in the program.

The priority of the three methods increases sequentially.

Lifecycle Timing Method

The session cookie is established from this cookie to closed by the browser.

Set the expiration time for a cookie indicates that the cookie expires after the cookie is established and the time is accumulated to the lifecycle.

It refers to the time interval between two sessions used by the client. If the time interval exceeds the lifecycle, the session becomes invalid. Otherwise, the session remains valid. The default life cycle is 30 minutes.

CookieAndSessionContact

Generally, session IDs are stored in the client memory as session cookies. When the browser is closed, the session cookies are deleted. Therefore, after closing the browser, you cannot find the session cookie that originally stored the session ID. Therefore, you cannot find the original session. However, the original session is also stored in the memory of the server, it will not be deleted from the server memory until it reaches the lifecycle.

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.