How cookies work?
Cookie is a fundamental technology in web browsing, primarily used to maintain state between the server and client. Its working principle can be divided into several steps:Server Sets Cookies:When you first visit a website, the server may send one or more cookies to your browser via the header in the HTTP response. For example, if you log in to a website, the server may send a cookie containing your session information so that it can remember your identity.Browser Stores Cookies:After receiving the cookie, the browser stores it locally based on its attributes (such as expiration, path, and domain). As long as the cookie has not expired and subsequent requests comply with the cookie's sending rules, the browser retains it.Browser Sends Cookies:In subsequent requests to the same server, the browser automatically sends the previously stored cookie for that server via the header in the HTTP request. This allows the server to recognize an established session and process the information in the cookie, such as maintaining the user's login state.Server Reads and Responds:After reading the cookie information, the server can retrieve previously stored state data, such as user ID and preferences. The server can customize the response content based on this information, such as displaying your username or loading your personal configuration.Updating and Deleting Cookies:The server can update the cookie content at any time by including a new header in the HTTP response. Similarly, to delete a cookie, the server sends a header with a past expiration time, and the browser automatically deletes it.For example, in user authentication: when you log in to a forum, enter your username and password, and the server verifies your credentials. Once verified, the server sends a cookie containing a unique session identifier to your browser. Whenever you browse different pages of the forum, your browser sends this cookie, and the server recognizes that you are logged in and provides the corresponding services.In summary, cookies are a simple yet powerful mechanism that enables the stateless HTTP protocol to maintain state information, providing users with seamless and personalized web experiences.