Home > Web Front-end > JS Tutorial > Let you understand the difference and usage of session and cookie (picture and text tutorial)

Let you understand the difference and usage of session and cookie (picture and text tutorial)

亚连
Release: 2018-05-19 09:45:53
Original
3715 people have browsed it

This article mainly introduces the working principle, difference and usage of session and cookie, as well as the advantages and disadvantages during use. By listing the differences and principles, readers can better understand the relationship between the two. Friends in need can refer to it. Next

Cookie Concept

When browsing certain websites, these websites will store some data on the client for tracking the use of the website. User, implement user-defined functions.

Whether to set the expiration time:

If the expiration time is not set, it means that the cookie life cycle is during the browser session, as long as Close the browser and the cookie will disappear.
This cookie whose life span is the browsing session is a session cookie;

Storage:
Generally stored in memory, not on the hard disk ;
If an expiration time is set, the browser will save the cookies on the hard drive. If you close and reopen the browser, these cookies will still be valid until the set expiration time is exceeded;
Cookies stored on the hard drive can be stored in different locations. Shared between browser processes, such as two IE windows.
Different browsers have different processing methods for cookies stored in memory.

Principle:

If the browser uses cookies, then all data is saved on the browser side.
For example, after you log in, the server settings Cookie username (username), then when you request the server again, the browser will send the username piece to the server. These variables have certain special marks.
The server will interpret it as a cookie variable.
So as long as the browser is not closed, the cookie variable will always be valid, so it can be guaranteed not to be disconnected for a long time.
If you can intercept a user's cookie variable and then forge a data packet and send it over, then the server will still think you are legitimate. Therefore, the possibility of being attacked using cookies is relatively high.
If the validity time is set, it will save the cookie on the client's hard drive. The next time you visit the website, the browser will first check whether there is a cookie. If there is, it will read the cookie. Then sent to the server.
If you save a forum cookie on your machine, the validity period is one year. If someone invades your machine, copies your cookie, and puts it in the directory of his browser, then he can log in to the website. When you log in with your identity.
So cookies can be forged.
Of course, you need some ideas when forging. You can directly copy the cookie file to the cookie directory, but the browser will not recognize it.
It has an index.dat file, which stores the creation time of the cookie file and whether it has been modified. So you must first have the cookie file of the website, and you must deceive the browser in terms of guaranteed time.
I once did an experiment on the school's vbb forum, copied other people's cookies to log in, and pretended to use other people's names to post Post, no problem at all.

Cookie usage:

  setcookie("user","zy",time()+3600); 设置user为zy,一小时之后失效;
  $_COOKIE['user'];     取回user值(名字)
  setcookie("user","",time()-3600); 删除cookie,第二个参数为空,第三个时间设置为小于系统的当前时间即可.
Copy after login

Or set it in your browser

When using Cookie, the Cookie automatically generates a text file and stores it in the temporary Cookie folder of the IE browser. The specific steps to delete the Cookie file using the browser are
>Select Tools/internet options in the IE browser command, open the Internet Options dialog box,
                                                                                                                                               Click the Delete Cookie button in the General tab, and click the OK button in the pop-up dialog box to successfully delete all Cookie files.
 
The concept of Session

Session is a HashTable-like structure stored on the server side (the implementation of each web development technology may be different, so it is directly called HashTable below) To store user data;

Function:

It is a collection of objects stored on the server side to realize data transfer between web pages.

Principle:

When a user requests an Asp.net page, the system will automatically create a Session; when exiting the application or closing the server, the Session will be revoked. When the system creates a Session, it will allocate a long string identifier to manage and track the Session.
The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or may use a hash table) to save information.
     
Save:

It is stored in the memory process of the Server segment, and this process is quite unstable and often restarts. If it is restarted, the Session will become invalid and the user must log in again. The user experience is quite poor. For example, when the user fills in the Information, the Session will expire when it is about to end and jump directly to the login page;

Have you already created a session:

When the program needs to create a session for a client request session, the server first checks whether the client's request contains a session identifier (called session id).

If it is included, it means that a session has been created for this client before, and the server will follow the session ID Retrieve this session using the id.... Use (if not retrieved, a new one will be created),

If the client request does not contain the session id, create a session for the client and generate a session with this session The associated session id,

The value of the session id should be a string that is neither repeated nor easy to find patterns to counterfeit. This session id will be returned to the client in this response. save.

(Summary: When creating a session, the server checks whether the client contains a session identifier. If so, it retrieves the session according to the session id, otherwise it has to create a new one.)

The client implementation form of Session (that is, the saving method of Session ID):

Generally, browsers provide two ways to save, and the other is for programmers to customize the implementation using html hidden fields. :

[1] Using Cookie to save, this is the most common method. The implementation of the "Remember My Login Status" function in this article is officially based on this method.

The server sends the Session ID to the browser by setting a cookie.

If we do not set this expiration time, then this cookie will not be stored on the hard disk. When the browser is closed, the cookie will disappear and the Session ID will be lost.

If we set this time to a number of days later, then this cookie will be saved on the client's hard drive. Even if the browser is closed, this value will still exist. The next time you visit the corresponding website, The same will be sent to the server.


[2] The method of using URL additional information is the same as we often see aaa.jsp?JSESSIONID=* on JSP websites. This method is the same as the first method where the cookie expiration time is not set. (URL rewriting means appending the session id directly to the end of the URL path.)


[3] The third way is to add a hidden field to the page form. This The first method is actually the same as the second method, except that the former sends data through GET, and the latter uses POST to send data. But obviously the latter is more troublesome.
Form hidden field means that the server will automatically modify the form and add a hidden field so that the session id can be passed back to the server when the form is submitted. For example:
                                                                                         
;
In fact, this technique can be simply replaced by applying URL rewriting to the action.

# Session:

User information Before saving to session, start; SESSION_START (); Start the session
$ _Session ['User'] ="zy"; Set user name
unset($_SESSION['user']); Destroy user name
session_destory(); Lose stored session data

The difference between cookie and session:         

1

, cookie data is stored on the client’s browser, and session data is placed on the server.

                                                                                                                                                                                                                                                                # session_id, the server determines the corresponding user data flag based on the current session_id to determine whether the user is logged in or has certain permissions.
Since the data is stored on the server, you cannot forge it, but if you can obtain the session_id of a logged-in user, you can also successfully forge the user's request using a special browser.
Session_id is randomly assigned when the server and client are connected. Generally speaking, there will be no duplication. However, if there are a large number of concurrent requests, there is the possibility of duplication. I have encountered it once.
Log in to a website and start showing your own information. After a period of time, when it is refreshed, it actually shows the information of others.

Session is a server-side storage space maintained by the application server. When the user connects to the server, a unique SessionID will be generated by the server, and the SessionID is used as the identifier to access the server-side Session storage space. The data of SessionID is saved to the client and saved with Cookie. When the user submits the page, the SessionID will be submitted to the server to access the Session data. This process does not require developer intervention. So once the client disables cookies, the Session will also become invalid.

      

2. Cookies are not very safe. Others can analyze the COOKIE stored locally and conduct COOKIE deception. Sessions should be used for security reasons.

                                                                                                                                                                      will be saved on the server for a certain period of time. When access increases, it will take up more of your server's performance. In order to reduce server performance, COOKIE should be used.

                                                                                                                   The data saved by a single cookie cannot exceed 4K, and many browsers limit a site to save a maximum of 20 cookies. (Session objects have no limit on the amount of data stored, and more complex data types can be saved.)

Note:

Sessions can easily expire and the user experience is very Poor;

Although cookies are not secure, they can be encrypted;

Cookies are also divided into permanent and temporary ones;

Browsers have a cookie ban function, but most users do not Will not set it;

Be sure to set the expiration time, otherwise it will disappear when the browser is closed;

For example:

The password remembering function is Use a permanent cookie to be written on the client computer. The next time you log in, the cookie information will be automatically sent to the server.

Application is global information, which is shared by all users. For example, it can record how many users have logged in to this website and display this information to all users.

The biggest difference between the two is the life cycle. One is from IE startup to IE shutdown. (As soon as the browser page is closed, the session disappears)

The other is the preset life cycle, or permanent storage local files. (cookie)

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

node

js

Detailed explanation of the steps to connect to mysql database

## to nodejsWhat are the ways to encrypt passwords

vue processes the data obtained by storejs


The above is the detailed content of Let you understand the difference and usage of session and cookie (picture and text tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template