Talking about the difference and connection between session and Cookie

Source: Internet
Author: User
Tags file size session id time limit
first, the concept of the session

Session is stored on the server side, similar to the session structure to hold user data, when the browser first send a request, the server automatically generated a session and a session ID to uniquely identify the session and send it through the response to the browser. When the browser sends a request for the second time, the session ID in the previous server response is placed in the request and sent to the server, the server extracts the session ID from the request and compares it with all saved session IDs to find the corresponding session of the user.

In general, the server will save the session for a certain amount of time (default 30 minutes), and after the time limit, the session will be destroyed. Before destroying, the programmer can temporarily store some of the user's data in the session as key and value. Of course, there is also the use of the database to save the session after serialization, the advantage is that there is no time limit, the disadvantage is that with the increase in time, the database will rapidly expand, especially when the traffic increases. In general, take the previous approach to relieve server pressure. Second, the client implementation form of session (that is, the session ID preservation method)

The General browser provides two ways to save, and one that programmers use to customize the implementation of HTML-hidden fields:

[1] Use of cookies to save, this is the most common method, this article "Remember my login status" feature implementation is formally based on this way. The server sends the session ID to the browser by setting a cookie. If we do not set this expiration time, then this cookie will not be stored on the hard disk, and when the browser is closed, the cookie disappears and the session ID is lost. If we set this time to a few days later, then this cookie will be saved on the client hard drive, even if the browser is closed, the value still exists, and the next time you visit the site, it will be sent to the server.

[2] How to use the URL to append information, that is, like we often see JSP site will have aaa.jsp? Jsessionid=* the same. This is the same way that the first method does not set the cookie expiration time.

[3] The third Way is to add hidden fields in the page form, which is actually the same as the second way, except that the former sends the data by means of a GET, which uses post to send the data. But obviously the latter is more troublesome.

The difference between a cookie and a session:

The cookie data is stored on the client side and the session data is saved on the server.

Simply put, when you log on to a website, if the Web server side uses the session, then all the data is stored on the server, the client each time the server is requested to send the current session of the SessionID, The server determines the appropriate user data flag based on the current SessionID to determine whether the user is logged on, or has some kind of permission. Since the data is stored on the server, you can't forge it, but if you can get the SessionID of a logged-on user, it can be successful to forge the user's request with a special browser. SessionID is a server and client link when randomly assigned, generally there will be no duplication, but if there is a large number of concurrent requests, there is no possibility of duplication, I have encountered once. Login to a website, start to display their own information, and so on for a period of time expired, a refresh, actually show someone else's information.

If the browser is using a cookie, then all the data is stored on the browser side, such as when you log in, the server set the cookie User name (username), then, when you request the server again, the browser will username a piece sent to the server, These variables have certain special markings. The server is interpreted as a cookie variable. So as long as you do not close the browser, then the cookie variable is always valid, so it can be guaranteed for a long time not to drop the line. If you can intercept a user's cookie variable and then forge a packet to send the past, the server still thinks you're legit. Therefore, the use of cookies is more likely to be attacked. If it is set to a valid time, then it will save the cookie on the client's hard disk, the next time you visit the website, the browser first check whether there is a cookie, if any, read the cookie, and then sent to the server. If you save a forum cookie on a machine that is valid for one year, if someone invades your machine, copies your cookie, and places it under the directory of his browser, then he or she logs in as your identity. So a cookie can be forged. Of course, the forgery of the need for ideas, directly copy the cookie file to the cookie directory, the browser is not recognized, he has a index.dat file, stored the cookie file set up time, and whether there is modification, so you must first have to have the site of the cookie file, and to ensure that the time to deceive the browser, once in the school's VBB forum has done experiments, copy other people's Cookie login, take the name of others to post, no problem at all.

Session is a server-side storage space maintained by the application server, when the user connects to the server, a unique SessionID is generated by the server, which uses the SessionID as an identifier to access the server-side session storage space. And SessionID this data is saved to the client, saved with a cookie, when the user submits the page, the SessionID will be submitted to the server side, to access the session data. This process is not a developer intervention. So once the client disables cookies, the session will also expire.

The server can also pass the SessionID value through URL rewriting, so it is not entirely dependent on cookies. If the client cookie is disabled, the server can automatically save the session value by rewriting the URL, and the process is transparent to the programmer.

You can try it, even if you do not write cookies, use Request.getcookies (), the length of the cookie array is also 1, and the name of this cookie is jsessionid, and there is a long binary string, Is the value of the SessionID. Three: Session and Cookie Difference and contact:

Cookies are part of a session object. However, the cookie does not account for server resources, is a text file that has client side memory or a cookie, and "Session" consumes server resources. So try not to use the session and use cookies. But we generally believe that cookies are unreliable, the session is reliable, but at present many famous sites have also been cookies. Sometimes in order to resolve the page processing after disabling cookies, url rewriting techniques are often used to invoke a number of useful methods in the session to get the data from the session and then place the page.

Cookie and Session Application scenarios:
The security of cookies has always been controversial. Although cookies are stored on this computer, their information is completely visible and easy to edit locally, which can often cause a lot of security problems. So the cookie should not be used, in the end how to use, there is a need to give a baseline.

Let's take a look at what the website's sensitive data is.

Login verification information. The usual use of the session ("Logon") =true or False form.
User's personal information, such as name, etc., in some cases, need to be saved in the session
Content information that needs to be passed between pages, such as survey work, takes several steps. Each step of the information is stored in the session, and finally in the unified update to the database.

Of course there will be many, here are some of the more typical
If a person is withdrawn to don't want to touch the session, because he thinks, if the user accidentally closed the browser, then the previous saved data are all lost. So, he decided to use the session as a means to store it with cookies, which is entirely feasible, and the basic operation is exactly the same as the session. So, for the above 3 typical examples, do an analysis
Obviously, as long as a deliberate illegal intruder, know that the site to verify the login information of the session variables, then he can edit the cookies in advance, put into the cookie directory, so that can be successfully verified. This is not very scary.
Cookies are completely visible, and even if the programmer sets the lifecycle of the cookie (for example, only valid for the duration of the user session), it is not safe. Suppose the user forgets to close the browser or a malicious person to stun the user, the loss of the user will be huge.
This is as simple as the point where it is easy for someone to steal important personal information. However, one of the problems is that it is possible that the amount of data information is too large to make the file size of cookies soar. This is not what users want to see.

Obviously, cookies are not such a good cookie. However, the existence of cookies, of course, has its reasons. It gives programmers more room to play with programming skills. So, use cookies to have a bottom line. This bottom line is generally followed by the following principles.
Do not save private information.
Any important data, it is best to save data by encrypting form (the simplest can be used urlencode, of course, can also use a perfect reversible encryption method, unfortunately, it is best not to use MD5 to encrypt).
Whether to save the login information, you need to have the user's own choice.
Longer than 10K of data, do not use cookies.
Also do not use cookies to play a little game that surprises customers. Iv. The most typical applications of cookies are:

(a): Determine whether the user has logged on to the site, so that the next time you log in directly. If we delete a cookie, each login must be re-filled with information about the login.

(ii): Another important application is the processing and design of classes in the "Shopping cart". Users may select different items on different pages of the same site for a period of time, can write this information to a cookie, and extract the information from the cookie at the final payment, although there are security and performance issues that need to be considered.

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.