search
HomeWeb Front-endJS TutorialSummary 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. Introduction
After 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 a

text 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

Development
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 location
Cookie 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. .

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

Storage
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;
Cookies can only save string types, in the form of text
Application scenarios
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

Summary of the differences between Cookie and Session

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 access
If the path parameter is set in the cookie, then cookies under different paths on the same website cannot access each other.
Disadvantages

Summary of the differences between Cookie and Session

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

Summary of the differences between Cookie and Session

Summary of the differences between Cookie and Session

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

Storage location
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 used
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.

Storage
sessionNo size limit
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)
Application scenarios
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.
  1. Shopping cart in the online mall
  2. Save user login information
  3. Put certain data into the session for use by different pages of the same user
  4. Prevent users from logging in illegally
Access
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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.