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
Storage locationsession 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.
- Shopping cart in the online mall
- Save user login information
- Put certain data into the session for use by different pages of the same user
- Prevent users from logging in illegally
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Which folder does the browser cache the video in? When we use the Internet browser every day, we often watch various online videos, such as watching music videos on YouTube or watching movies on Netflix. These videos will be cached by the browser during the loading process so that they can be loaded quickly when played again in the future. So the question is, in which folder are these cached videos actually stored? Different browsers store cached video folders in different locations. Below we will introduce several common browsers and their

DNS (DomainNameSystem) is a system used on the Internet to convert domain names into corresponding IP addresses. In Linux systems, DNS caching is a mechanism that stores the mapping relationship between domain names and IP addresses locally, which can increase the speed of domain name resolution and reduce the burden on the DNS server. DNS caching allows the system to quickly retrieve the IP address when subsequently accessing the same domain name without having to issue a query request to the DNS server each time, thereby improving network performance and efficiency. This article will discuss with you how to view and refresh the DNS cache on Linux, as well as related details and sample code. Importance of DNS Caching In Linux systems, DNS caching plays a key role. its existence

A Beginner's Guide to Guava Cache: Speed Up Your Applications Guava Cache is a high-performance in-memory caching library that can significantly improve application performance. It provides a variety of caching strategies, including LRU (least recently used), LFU (least recently used), and TTL (time to live). 1. Install Guava cache and add the dependency of Guava cache library to your project. com.goog

Title: Caching mechanism and code examples of HTML files Introduction: When writing web pages, we often encounter browser cache problems. This article will introduce the caching mechanism of HTML files in detail and provide some specific code examples to help readers better understand and apply this mechanism. 1. Browser caching principle In the browser, whenever a web page is accessed, the browser will first check whether there is a copy of the web page in the cache. If there is, the web page content is obtained directly from the cache. This is the basic principle of browser caching. Benefits of browser caching mechanism

PHPAPCu (replacement of php cache) is an opcode cache and data cache module that accelerates PHP applications. Understanding its advanced features is crucial to utilizing its full potential. 1. Batch operation: APCu provides a batch operation method that can process a large number of key-value pairs at the same time. This is useful for large-scale cache clearing or updates. //Get cache keys in batches $values=apcu_fetch(["key1","key2","key3"]); //Clear cache keys in batches apcu_delete(["key1","key2","key3"]);2 .Set cache expiration time: APCu allows you to set an expiration time for cache items so that they automatically expire after a specified time.

There is a close interaction between the CPU (central processing unit), memory (random access memory), and cache, which together form a critical component of a computer system. The coordination between them ensures the normal operation and efficient performance of the computer. As the brain of the computer, the CPU is responsible for executing various instructions and data processing; the memory is used to temporarily store data and programs, providing fast read and write access speeds; and the cache plays a buffering role, speeding up data access speed and improving The computer's CPU is the core component of the computer and is responsible for executing various instructions, arithmetic operations, and logical operations. It is called the "brain" of the computer and plays an important role in processing data and performing tasks. Memory is an important storage device in a computer.

How to Export Browser Cache Videos With the rapid development of the Internet, videos have become an indispensable part of people's daily lives. When browsing the web, we often encounter video content that we want to save or share, but sometimes we cannot find the source of the video files because they may only exist in the browser's cache. So, how do you export videos from your browser cache? This article will introduce you to several common methods. First, we need to clarify a concept, namely browser cache. The browser cache is used by the browser to improve user experience.

Exploration of PHP caching technology: a powerful tool to improve website performance, specific code examples are required Introduction: With the rapid development of today's Internet, website performance is crucial to user experience and search engine rankings. As a commonly used programming language, PHP is widely used in website development. How to improve the performance of PHP websites has become an urgent issue for developers. One of the very important solutions is to use PHP caching technology. This article will explore the concept and specific technology of PHP caching, and come with code examples to help readers understand
