


Detailed explanation of the difference between cookies and sessions in PHP and summary of cookie and session usage, cookiesession
Detailed explanation of the difference between cookies and sessions in PHP and a summary of the usage of cookies and sessions. Cookiesession
Specifically, cookies are stored on the "client", The session is saved on the "server"
Cookies are implemented by extending the http protocol
Cookies mainly include: name, value, expiration time, path and domain;
If the cookie is not set to have a life cycle, it will be closed when the browser is closed. This kind of cookie is generally stored in memory rather than on the hard disk. If the life cycle is set, the opposite is true. It does not disappear when the browser is closed. These cookies are still valid. until the set expiration time is exceeded.
session stores information in a hash table-like form,
When the program needs to create a session for a client's request, the server first checks whether the client's request already contains a session identifier
(called session id). If it is included, it means that a session has been created for this client before. The server will retrieve this session according to the session id and use it (if it cannot be retrieved, it will create a new one). If the client requests If the session id is not included, create a session for this client and generate a session id associated with this session. The value of the session id should be a string that is neither repeated nor easy to find patterns for forgery. This The session id will be returned to the client in this response for storage. 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. Generally, the name of this cookie is similar to SEEESIONID. But cookies can be artificially disabled, and there must be other mechanisms to still pass the session id back to the server when cookies are disabled.
Advantages and disadvantages:
1. Cookie data is stored on the customer's browser, and session data is placed on the server.
2. Cookies are not very safe. Others can analyze the cookies stored locally and deceive them
Session should be used for security reasons.
3. The session will be saved on the server within a certain period of time. When access increases, it will take up more of your server’s performance
COOKIE should be used to reduce server performance.
4. The data saved by a single cookie cannot exceed 4K. Many browsers limit a site to save up to 20 cookies.
5. So personal suggestion:
Save important information such as login information as SESSION
If other information needs to be retained, it can be placed in COOKIE
Summary of the use of Session and Cookies:
Session and cookie are both built-in objects in asp.Net. As for their differences, I won’t go into details here. Now let’s talk about some more practical things:
We know that websites have a backend management system, which has two functions: login and logout. When logging in, we often save the user’s information in the session or cookie for later use. Then when logging in, we What should we pay attention to?
1. Store some sensitive things in the session. Less sensitive things can be stored in the session or cookies. For example, usernames are not very sensitive, but some browsers do not support the use of cookies, so we will Save it in the session, but the session is sometimes easily lost in the server, so we can use it in conjunction with cookies. That is to say, when the session is lost, if the cookie is still within the validity period we set, it can be used again Take the value from the cookie and put it into the session, so we'd better use session and cookie to save user name and other information at the same time or in the configuration file
Copy code The code is as follows:
You can also solve the problem of session loss
2. We hope that the background management will invalidate the session and log in again if there is no operation for a long time. You can use session.timeout=5, in minutes, which means that if there is no other operation within 5 minutes, it will be invalid. , or configure
3. Setting the cookie validity period
httpCookie.Expires = DateTime.Now.AddMinutes(2);
The cookie is valid for 2 minutes
4. When judging whether you have permission to access the web page, you can judge as follows:
if (Request.Cookies["httpCookie"] != null) { Session["admin"] = Request.Cookies["httpCookie"].Values["admin"].ToString(); } if (Session["admin"] == null) { this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请重新登 录');location.href='logins.aspx'</script>"); }
Let’s talk about what to do when logging out
1. The session and cookie values must be cleared when exiting. Now let’s briefly talk about the differences between several methods of session:
Session.clear(): means to clear all session key values in the session, but the session still exists, equivalent to Session.RemoveAll()
Session[“admin”]=null: Indicates that the value of the specified key will be cleared and released. It is different from session[“admin”]=””. It is cleared, but the session is not released, which is equivalent to session .Remove(“name”);
Session.Abandon() deletes the current Session object, and it will be a new Session next time.
The main difference is that when using Session.Abandon, the Session_End method (in InProc mode) is called. The Session_Start method will be fired when the next request comes. Session.Clear only clears all data in the Session and does not terminate the
Session, so those methods will not be called. The Abandon method is used to actively end the session. If this method is not called, the current session will automatically end when the session times out.
2. Let’s take a look at how to clear cookies
A. tpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get("tuser");
cookie.Expires = DateTime.Now.AddDays(-1);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
B. tpCookie httpCookie = Request.Cookies["httpCookie"];
httpCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(httpCookie);
Both methods AB can be used
3. So just clear the current value of the session, that is, Session["admin']=null. Just clear the cookie according to the above method
Suggestions and comments:
1. When exiting, we can create a logout page to write the time, which is better
2. No matter what operation is performed, if you can use If to determine whether it is empty, try your best to prevent the occurrence of a null pointer exception
The above is a detailed explanation of the difference between cookies and sessions in PHP and a summary of cookie and session usage introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message. Editor Will reply to everyone promptly. I would also like to thank you all for your support of the Bangkejia 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











Export password-protected PDF in Photoshop: Open the image file. Click "File"> "Export"> "Export as PDF". Set the "Security" option and enter the same password twice. Click "Export" to generate a PDF file.

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

The necessity of registering VueRouter in the index.js file under the router folder When developing Vue applications, you often encounter problems with routing configuration. Special...

Detailed explanation of XPath search method under DOM nodes In JavaScript, we often need to find specific nodes from the DOM tree based on XPath expressions. If you need to...

不同数据库系统添加列的语法为:MySQL:ALTER TABLE table_name ADD column_name data_type;PostgreSQL:ALTER TABLE table_name ADD COLUMN column_name data_type;Oracle:ALTER TABLE table_name ADD (column_name data_type);SQL Server:ALTER TABLE table_name ADD column_name data_

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

There are differences in the promotion methods of H5 and mini programs: platform dependence: H5 depends on the browser, and mini programs rely on specific platforms (such as WeChat). User experience: The H5 experience is poor, and the mini program provides a smooth experience similar to native applications. Communication method: H5 is spread through links, and mini programs are shared or searched through the platform. H5 promotion methods: social sharing, email marketing, QR code, SEO, paid advertising. Mini program promotion methods: platform promotion, social sharing, offline promotion, ASO, cooperation with other platforms.
