Home > Article > Web Front-end > Summary of the differences between Cookie and Session
This article brings you a summary of the differences between Cookies and Sessions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
HTTP Stateless Protocol
HTTP stateless protocol means that the protocol has no memory ability for transaction processing. The lack of status means that if subsequent processing requires the previous information, it must be retransmitted, which may result in an increase in the amount of data transferred per connection. On the other hand, the server responds faster when it does not need previous information. IntroductionAfter the emergence of Web applications that dynamically interact between clients and servers,
The stateless characteristics of HTTP have seriously hindered the implementation of these applications. After all, interaction needs to connect the past and the future. Simple The shopping cart program also needs to know what products the user has selected before. As a result, two technologies for maintaining the HTTP connection status came into being, one is Cookie, and the other is Session. HTTP itself is a stateless connection protocol. In order to support the interaction between the client and the server, we need to use different technologies to store state for the interaction, and these different technologies are Cookie and Session. Cookies are a solution for maintaining state through the client. By definition, a cookie is special information sent from the server to the client, and this information is stored on the client in the form of aDevelopmenttext file , and then the client sends a request to the server every time Bring these special messages. Let's be more specific: When a user uses a browser to visit a website that supports Cookies, the user will provide personal information including the user name and submit it to the server; then, the server will return the corresponding hypervisor to the client. This personal information will also be sent back along with the text. Of course, this information is not stored in the HTTP response body (Response Body) , but is stored in the HTTP response header (Response Header) ; When the client browser receives the response from the server, the browser will store the information in a unified location. For the Windows operating system, we can start from: [System Disk]:Documents and Settings[user name] The stored cookie is found in the Cookies directory; from then on, when the client sends a request to the server, it will send the corresponding cookie back to the server again. This time, the cookie information is stored in the HTTP request header (Request Header). italic text
With the implementation of technology such as Cookie, after the server receives a request from the client browser, it can obtain client-specific information by analyzing the Cookie stored in the request header, thereby dynamically generating information related to the request. Content corresponding to the client. Usually, we can see options like "Please remember me" on the login interface of many websites. If you check it before logging in, you won't need to perform repeated and cumbersome logins the next time you visit the website. Action, and this function is implemented through Cookie.A solution opposite to Cookie is Session, which maintains state through the server. Since the word Session contains many semantics, it is necessary to clarify the meaning of Session here. First of all, we usually translate Session into session, so we can call a series of interactive actions between the client browser and the server a Session. Starting from this semantics, we will mention the duration of the Session, what operations are performed during the Session, etc.; Secondly, Session refers to the storage space opened by the server for the client and the information saved in it. It is used to maintain status. Starting from this semantics, we will mention what content to store in the Session, how to obtain matching content from the Session based on the key value, etc.
To use Session, the first step is of course to create a Session. So when is the Session created? Of course, it is created while the server-side program is running. Applications implemented in different languages have different methods of creating a Session. In Java, it is created by calling the getSession method of HttpServletRequest (using true as a parameter). When creating a Session, the server will generate a unique Session id for the Session, and this Session id will be used to regain the created Session in subsequent requests; after the Session is created, you can call the Session-related The method adds content to the Session, and these contents will only be saved in the server, and only the Session id is sent to the client; when the client sends a request again, it will bring this Session id, and the server will Find the corresponding Session based on the Session id and use it again. It is through such a process that the user's status is maintained.
To sum up, HTTP itself is a stateless connection protocol. In order to support the interaction between the client and the server, we need to store the state for the interaction through different technologies, and these different technologies are Cookie and Session are .
Cookie
Storage locationCookie data is stored on the customer's browser, and the server can know the information;Usage method
If In the browser no expiration time is set , the cookie is saved in memory , and the life cycle ends when the browser is closed . This type of cookie is referred to as a session cookie. .StorageIf the cookie expiration time is set in the browser , the cookie is saved in the hard disk . After closing the browser, the cookie data will still exist until the expiration time. It disappears only after it is over.
The data saved by a single cookie cannot exceed 4KB, a server can save up to 20 Cookies on the client browser, and a browser can save up to 300 Cookies;Application scenarios
Cookies can only save string types, in the form of text
Cookie technology has 4 components: in the HTTP response report There is a cookie header line in the article; there is a cookie header line in the HTTP request message; a cookie file is retained in the client system and is managed by the user's browser; a back-end database located in the Web site
Determine whether the user has logged in to the website, so that automatic login (or remember the password) can be achieved the next time you log in.
If we delete cookies, the relevant login information must be filled in again each time you log in.
Save the last login time and other information. Save the last viewed page Browse count accessIf the path parameter is set in the cookie, then cookies under different paths on the same website cannot access each other.Disadvantages
Limited size, users can operate (disable) cookies, which limits functions, lower security, some states cannot be saved on the client, each time Every access requires sending cookies to the server, which wastes bandwidth. Cookie data has the concept of path, and cookies can be restricted to only belong to a certain path.
other
Carry cookies for data requests
Cookie data is always carried in the http request from the same origin (even if it is not needed), that is, the cookie is passed back and forth between the browser and the server ;
The cookie will be sent every time a new page is requested, which wastes bandwidth. In addition, the cookie needs to specify a scope and cannot be called across domains.
session data is placed on the server. The client does not know the information, but the session can be managed persistently in a special way (memcache, redis);Usage
When the session is created, and session consistency issues
session will be saved on the server within a certain period of time. When access increases, it will It takes up more performance of your server. In order to reduce server performance, cookies should be usedStorage
When the program needs to create a session for a client's request, the server first checks the client's requestWhether a session identifier (called session id) has been included . If it has been included, it means that a session has been created for this client before, and the server will pass this session according to the session id. Use to retrieve it (if cannot be retrieved, a new will be created). If the client request does not contain a session id, a session will be created for the client and a session id associated with this session will be generated. The value of the session id should be a string that is neither repetitive nor easy to find patterns to counterfeit . This session id will be returned to the client for storage in this response. The method of saving this session ID can use cookies, so that during the interaction process, the browser can automatically send this identification to the server according to the rules.Usually use cookies to store the sessionid to the client. During the interaction, the browser sends the sessionid to the server according to the rules. If the user disables cookies, URL rewriting must be used, which can be achieved through response.encodeURL(url)
; the end of the API for encodeURL is that when the browser supports cookies, the url does not do any processing; when the browser does not When cookies are supported, the URL will be rewritten and the SessionID will be spliced to the access address.
sessionNo size limitApplication scenarios
What is saved in the session is the object. The session is saved through a data structure similar to Hashtable, which can support any Type of object (session can contain multiple objects)
Session is used to save the private information of each user. The value of the variable is saved on the server side, and different customers are distinguished through SessionID.
Session cannot distinguish paths. During the same user's visit to a website, all sessions can be accessed from anywhere.
Disadvantages
The more things the Session saves, the more server memory is occupied. For websites with a large number of online users, the server's memory pressure will be relatively large and depends on cookies (sessionID is saved in cookie), if you disable cookies, you need to use URL rewriting, which is unsafe. Creating Session variables is very arbitrary and can be called at any time. It does not require developers to do precise processing. Therefore, excessive use of session variables will cause code Unreadable and difficult to maintain.
The above is the detailed content of Summary of the differences between Cookie and Session. For more information, please follow other related articles on the PHP Chinese website!