Cookie(4KB)(saved on the client)
introduce
A “Cookie” is a small amount of information that is sent by a web server to be stored in a web browser so that it can be read back from that browser the next time the unique visitor returns to the web server.
A Cookie is a text file stored in the browser directory and stored in RAM while the browser is running. Cookies can also be stored on your computer’s hard drive once you log out of the site or web server. All cookies are terminated when the visitor ends his browser conversation.
Why use
Marking user status
First, we need to understand the concept that web applications are transmitted using HTTP, which is a stateless protocol with no memory for transaction processing. The lack of state means that if the previous information is needed for subsequent processing, it must be retransmitted, which can result in an increase in the amount of data transferred per connection. On the other hand, the server responds faster when it doesn’t need the previous information.
When to produce
When the client sends a request to the server, the server sends a Cookie to the client and the browser saves the Cookie. There are two ways to save the Cookie. One is that the browser saves the CCookie in memory, and the other is to save it in the client’s hard disk. Each subsequent HTTP request browser sends a Cookie to the server.
Note: Cookies can be disabled by the browser and set-cookies can be disabled by the server.
Cookie life cycle
Cookies can be created with an Expire value, which is the lifetime of the Cookie. Cookies will be valid for a period of time, but will be cleared in milliseconds.
Note: The Cookie life cycle is set to “0” or negative value, so that when the browser is closed, the Cookie will be cleared immediately, and user information will not be recorded, which is more secure.
attribute
Attributes are semicolons (;) Separation of multiple
disadvantages
-
Quantity is limited. A browser can create a maximum of 300 cookies and each Cookie cannot exceed 4KB. Each Web site can set a maximum of 20 cookies
-
Security cannot be guaranteed. Cross-site scripting attacks usually tend to use the site vulnerability script code in the web page or web page script code refer to the third method, there exist the possibility of cross-site scripting attacks, when cross-site scripting attacks, the script command will read the current all the cookies content of the site (no longer exists Cookie scope restrictions), The Cookie content is then somehow submitted to the specified server (for example, AJAX). Once a Cookie falls into the hands of an attacker, it will regain its value.
-
Browsers can disable cookies. After cookies are disabled, they cannot enjoy the convenience brought by cookies.
Session(Unlimited size)(stored on the server)
introduce
Session: In computers, especially in network applications, it is called “Session control”. The Session object stores properties and configuration information required for a specific user Session. This way, variables stored in the Session object will not be lost when the user jumps between Web pages of the application, but will persist throughout the user Session. When a user requests a Web page from an application, the Web server automatically creates a Session object if the user does not already have a Session. When a session expires or is abandoned, the server terminates the session.
Session is another mechanism to record the client status. The difference is that cookies are stored in the client browser, while the session is stored on the server. When the client browser accesses the server, the server records the client information in some form on the server, which is the session. The client browser only needs to look up the client’s status from the Session when it visits again.
Why use
A little bit more security than cookies.
Because many third parties can obtain this Cookie, the server cannot determine whether the Cookie is sent by a real user, so the Cookie can be forged to achieve login and some HTTP requests. If sessions are a little more secure than cookies, let’s start with the concept of SessionID. What is a SessionID? When the client requests the server for the first time, the server will create a Session for the client and calculate the ID of a Session through a special algorithm. The next time the client requests resources (the Session has not expired), the browser will place the sessionID(essentially cookies) in the request header. After receiving the request, the server gets the SessionID of the request. The server finds the session with this ID and returns it to the requester for use.
Session Life Cycle
According to the requirements, generally, half an hour. For example, if you log in to a server, the server returns a sessionID, and there are no HTTP requests to the server within half an hour after successful login. If you make an HTTP request after half an hour, you will be prompted to log in again.
defects
Because sessions are stored on the server, too many sessions may cause pressure on the server. Relieve server stress through automatic cleanup mechanism. lo
The implementation process
- Generate global unique identifier session_id on the server side;
- Create datastore space corresponding to this session_ID in the server memory.
- Send session_ID as global unique identifier to client through cookie;
- The session_ID will be sent to the server via cookies in the request header when the client accesses the server in the future.
- The server uses session_id to fetch data from this identifier on the server side
- What if cookies are disabled on the client’s browser? In this case, session tracking is typically done using a technique called URL rewriting, where the URL is appended to each HTTP interaction
attribute
SessionStorage(5MB or larger)(save client)
introduce
The sessionStorage property allows you to access a sessionStorage object corresponding to the current source.
It is similar to localStorage except that data stored in localStorage does not have an expiration date, while data stored in sessionStorage is cleared when the page session ends.
Note: The data stored in sessionStorage or localStorage is specific to the page protocol. The sessionStorage of example.com and example.com is isolated from each other.
The life cycle
- The page session remains as long as the browser is open, and reloading or restoring the page preserves the original page session (recovering data).
- The context of the top-level browsing session is copied as the context of the new session when opening a page in a new TAB or window (jumping from the project to a new page), unlike session cookies.
- Opening multiple Tabs pages of the same URL will create a separate sessionStorage.
- Closing the corresponding browser Window (Window)/TAB clears the corresponding sessionStorage.
Suitable for: Solve the problem of sharing data caused by multiple project support
use
Global object – sessionStorage
// Save data to sessionStorage
sessionStorage.setItem('key'.'value');
// Get data from sessionStorage
let data = sessionStorage.getItem('key');
// Delete saved data from sessionStorage
sessionStorage.removeItem('key');
// Delete all saved data from sessionStorage
sessionStorage.clear();
Copy the code
- Set the storage
sessionSTorage.setItem(key, value)
- Read the storage
sessionSTorage.getItem(key)
- Deleting a storage
sessionSTorage.removeItem(key)
- Delete all storages.
sessionSTorage.clear()
Note: For objects, integer keys are automatically converted to strings.
LocalStorage(5MB or larger)(save client)
introduce
The read-only localStorage property allows you to access a Document source (Origin) object Storage;
The stored data is saved in the browser session. LocalStorage is similar to sessionStorage, but the difference is that the data stored in localStorage can be retained for a long time. When the browser/TAB is closed, the data still exists.
use
Global object – localStorage
// Set the data
localStorage.setItem('myCat'.'Tom');
// Read data
let cat = localStorage.getItem('myCat');
// Remove specified data
localStorage.removeItem('myCat');
// Remove all
localStorage.clear();
Copy the code
- Set up the data
localStorage.setItem(key, value)
- Read the data
localStorage.getItem(key)
- Remove specified data
localStorage.removeItem(key)
- Remove all
localStorage.clear()
Note: Key-value pairs in localStorage are always stored as strings. Note that key-value pairs are always stored as strings compared to JS objects, which means that numeric types are automatically converted to string types
Cookie and Session comparison
-
Stay in shape:
- Cookies are saved on the browser side
- The session is stored on the server side
-
Usage:
- Cookie mechanism:
If the expiration time is not set in the browser, the cookie is stored in memory and its life cycle ends when the browser closes. This cookie is referred to as a session cookie. If a cookie expiration time is set in the browser, the cookie is saved in the hard disk. After the browser is closed, the cookie data still exists until the expiration time ends.
- The session mechanism:
When the server receives a request and needs to create a session object, it first checks whether the client request contains a sessionID. If there is a sessionID, the server returns the corresponding session object based on the ID. If the client request does not have a session ID, the server creates a new session object and returns the session ID to the client in the response. Generally, the sessionid is stored to the client in cookie mode, and the browser sends the sessionid to the server according to the rules during the interaction. If the user disables cookies, URL rewriting is required, which can be achieved through Response.encodeURL (URL). When the browser supports cookies, the URL does nothing. When the browser does not support cookies, the URL will be overwritten to concatenate the SessionID to the access address.
-
Storage contents:
- Cookies can only be saved as strings, as text
- Sessions are stored in a data structure similar to Hashtable and can support any type of object (a session can contain multiple objects).
-
Storage size:
- Cookie: the data saved by a single cookie cannot exceed 4kb.
- There is no limit to the session size.
-
Security:
- Cookie: attacks against cookies: cookie spoofing, cookie interception;
- Session is more secure than cookie.
-
Application Scenarios:
-
Cookies:
- Determine if the user has logged in to the site so that the next time you log in, you can automatically log in (or remember your password).
- Save information such as the time of the last login.
- Save the page you last viewed
- Browse the count
-
Session:
- Shopping cart in online shopping mall
- Saves user login information
- Put some data into a session for use by different pages of the same user
- Prevent unauthorized login
-
Compare localStorage with sessionStorage
- Life cycle:
- The localStorage life cycle is permanent and needs to be manually cleared;
- The sessionStorage life cycle is valid only for the current session and is cleared automatically after closing the browser/TAB
Cookie compares with WebStorage(Local/Session)
-
Life cycle:
- localStorage:
The life cycle of localStorage is permanent, and the data in localStorage does not disappear after the page or browser is closed. LocalStorage data will never disappear unless it is actively deleted.
- sessionStorage:
The sessionStorage lifetime is valid only for the current session. SessionStorage introduces the concept of a “browser window.” sessionStorage is data that is always present in the same window. As long as the browser window is not closed, the data remains even if the page is refreshed or another page is entered. However, sessionStorage is destroyed when the browser window is closed. At the same time independently open the same window the same page, sessionStorage is not the same.
-
Storage size:
- The size of data stored in localStorage and sessionStorage is usually 5MB or larger
-
Storage location:
- Both localStorage and sessionStorage are stored in the client and do not interact with the server.
-
Storage contents:
- LocalStorage and sessionStorage can only store string types, and for complex objects can be handled using Stringify and Parse for JSON objects provided by ECMAScript
-
Obtaining method: L
- LocalStorage:
window.localStorage:Object
; - sessionStorage:
window.sessionStorage:Object
. - cookie:
document.cookie:String
- LocalStorage:
WebStorage advantages
- More storage space: Cookies are 4KB, WebStorage is 5MB;
- Save network traffic: WebStorage will not be transmitted to the server, stored in the local data can be directly obtained, not like cookies, the United States word request will be transmitted to the server, so reduce the client and server interaction, saving network traffic;
- SessionStorage is handy for data that only needs to be saved during a set of pages and then discarded after the user closes the browser.
- Fast display: Some data is stored on WebStorage, plus the browser’s own cache. It’s much faster to get data locally than it is to get data from the server.
- Security: WebStorage will not be sent to the server with HTTP headers, so security is relatively higher than cookies, there is no concern about interception, but there are still forged problems;
- Convenient to use: WebStorage provides some methods, data operation is more convenient than cookie;