If there are any mistakes, please point them out in the comments so I can correct them myself
Author: thomaszhou
-
The difference between cookies and sessions
- Cookie data is stored on the client’s browser and session data is stored on the server
- Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. For security, session should be used. Sessions are commonly used for user authentication
- The session is stored on the server and the client does not know the information in it; Instead, cookies are stored on the client side, and the server can see the information in them
- Sessions are stored on the server for a certain period of time. When the number of accesses increases, the performance of your server will be affected. In order to reduce the performance of your server, you should use cookies
- The session holds objects, and the cookie holds strings
- Session cannot distinguish paths. During the same user’s visit to a website, all sessions can be accessed anywhere. However, if the path parameter is set in cookies, cookies under different paths in the same website cannot be accessed to each other
-
Understand the relationship between session and cookie in depth
Session: a data structure stored on the server to track user status. This data can be stored in clusters, databases, and files.
Cookie: it is a mechanism for the client to save user information and record some user information. It is also a way to realize the Session.
- 1. HTTP is a stateless protocol, so when the server needs to record the status of users, it needs to use some mechanism to identify specific users, and this mechanism is Session. In a typical scenario like a shopping cart, when you click the order button, HTTP is stateless, so you don’t know which user is doing it, so the server creates a special Session for a particular user, identifies that user, and keeps track of that user, so it knows how many books are in the shopping cart. This Session is stored on the server and has a unique identifier. There are many ways to save sessions on the server, including memory, databases, and files. Session transfer should also be considered when clustering. In large websites, there is usually a special cluster of Session servers to store user sessions. In this case, Session information is stored in memory, and some caching services such as Memcached are used to store sessions.
- 2. How does the server identify a particular client? : This is where cookies come in. Each TIME an HTTP request is made, the client sends a Cookie to the server. In fact, most applications use cookies to realize Session tracking. When a Session is created for the first time, the server tells the client in the HTTP protocol that it needs to record a Session ID in the Cookie, and sends this Session ID to the server for each subsequent request. I knew who you were.
The running of a session depends on the session ID, which is stored in cookies
-
3. What if cookies are disabled by the browser on the client? In this case, session tracking is typically done using a technique called URL rewriting (passing session_id in the URL), where each HTTP interaction is followed by a parameter such as SID = XXXXX that the server identifies the user.
-
4. A common scenario for cookies is to automatically fill in the user name and password
Originally, session is an abstract concept. Developers abstract one-to-one interaction between user agent and server into “session” in order to realize operations such as interruption and continuation, and then derive “session state”, which is the concept of session.
A cookie is an actual thing, a header field defined in the HTTP protocol. Think of it as a back-end stateless implementation of session.
In order to circumvent the limitations of cookies, the “session” is often referred to today. It is usually implemented with the help of cookies and back-end storage, a more advanced session state implementation.
So cookies and sessions, you can either think of them as being at the same level or you can think of them as being at different levels. In terms of implementation, session is usually realized by cookie because of the existence of session ID, but this is not necessary. It can only be said that it is a kind of implementation scheme with good universality.
-
LocalStorage, sessionStorage and cookies
Common: both are saved in the browser and are of the same origin
Data storage
- Cookie data is always carried (even if it is not needed) in same-origin HTTP requests, i.e. cookies are passed back and forth between the browser and the server. Cookie data also has the concept of path, which can restrict cookies to a specific path
- SessionStorage and localStorage do not automatically send data to the server, only localStorage.
Storage data size
- The storage size limit is also different, cookie data cannot exceed 4K, and because cookies are carried with each HTTP request, cookies are only good for small data, such as session identifiers.
- SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more
Data Storage Validity Period
- SessionStorage: only valid until the current browser window closes;
- LocalStorage: always valid, always saved even when the window or browser is closed, locally stored and therefore used as persistent data;
- Cookie: Only valid before the set cookie expiration time, even if the window is closed or the browser is closed
Different scope
- SessionStorage is not shared across different browser Windows, even on the same page;
- localstorageIn all
The same window
Are shared; This means that as long as the browser is not closed, the data still exists - cookie: Is also at all
The same window
That is, as long as the browser is open, the data remains
Web Storage has setItem, getItem, removeItem, clear and other methods, unlike cookies need their own encapsulation setCookie, getCookie and other methods
-
SessionStorage and page JS data objects
The lifetime of a normal JS object in a page is only valid for the current page, so the data does not exist when the page is reloaded, such as refreshing the page or going to another page.
While sessionStorage as long as the same as the same window, refresh the page or enter a different page of the same origin, data always exist, that is to say, as long as the browser is not closed, data still exist ()
This section describes how to use cookies
Cookies can write good encapsulation, also can use directly has written here to recommend a good framework ‘jquery. Cookies, 2.2.0. Min. Js. Note and have a cookie. Can also be js, personal feel to do not have “jquery. Cookies. 2.2.0. Min. Js” works.
So let’s talk about the native use of JavaScript.
Cookie is stored as a name/value pair. For example, username=John Doe. The data here is a string.
JavaScript can create, read, and delete cookies using the document.cookie property. In JavaScript, create a cookie like this:
document.cookie="username=John Doe";
Copy the code
You can also add an expiration time (in UTC or GMT time) to the cookie. By default, cookies are deleted when the browser is closed:
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT";
Copy the code
You can use the path parameter to tell the browser the path of the cookie. By default, cookies belong to the current page.
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
Copy the code
Set the cookie
function setCookie(cname,cvalue,exdays) { var SetTime = new Date(); Settime.settime (settime.getTime ()+(exdays*24*60*60*1000)); // Set expires ="expires="+SetTime.toGMTString(); // Set expiration time document.cookie = cname +"=" + cvalue + "; "+ expires; // Create a cookie}Copy the code
Read the cookie
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if(c_start! =-1) { c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
Copy the code
Delete the cookie
Change the validity date of the cookie to yesterday.
Using jquery. Cookies. 2.2.0. Min. Js plug-ins
Add/modify cookies and set expiration time:
`$.cookies.set('cookie_id'.'cookie_value', { hoursToLive: 10 });
Copy the code
Here, the expiration time is set to 10 hours. You can also set the expiration time as follows:
expireDate = new Date();
expireDate.setTime( expireDate.getTime() + ( 10 * 60 * 60 * 1000 ) );
$.cookies.set('cookie_id'.'cookie_value', {expiresAt:expireDate});
Copy the code
To get a cookie
$.cookies.get('cookie_id');
Copy the code
Delete the cookie
$.cookies.del('cookie_id');
Copy the code
SessionStorage and localStorage usage
H5 for web storage support is very friendly, very simple to use
- setItem()
sessionStorage.setItem(keyName,value); // Store the value in the key field // or sessionStorage.keyName='value'; Eg: the sessionStorage. SetItem ("name"."thomas");
localStorage.getItem(keyName); // Get the local store value of the specified key // or var keyName=localStorage.key;
eg:sessionStorage.getItem("name");
Copy the code
I’ll just list the sessionStorage methods.
The other methods are basically the same as above, just change the prefix sessionStorage to localStorage
- getItem()
sessionStorage.getItem(keyName); Var keyName= sessionstorage.key; var keyName= sessionstorage.key; eg: sessionStorage.getItem("name");
Copy the code
- removeItem()
sessionStorage.removeItem(keyName); / / delete specified ke locally stored value of eg: sesisonStorage. RemoveItem ("name");
Copy the code
- clear()
Sessionstorage.clear () // Clear alllocalStorage of dataCopy the code