Home > Article > Backend Development > How to clear session in php
How to clear session in php: 1. Enable Session; 2. Set a number variable; 3. Get the value of session; 4. Clear the session through "unset".
The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
How to clear session in php?
Comparison of PHP Session and Cookie
Session: stored on the server side, there is no need to worry about the user disabling the session, but the load of the recorded file is The server is responsible.
Cookie: stored on the client. Some clients may disable cookies, but the server does not need to bear the load of recording files.
Each has its own advantages and disadvantages, so there is no problem of completely abandoning cookies. Some unimportant information can be stored with cookies, which reduces the load on some servers; but important information, such as user login For account numbers, etc., please use session as it will be safer.
Where to use Session
Usually if your website has a member login function or a shopping cart function, you can basically use session to help you record this information. In addition, if your members have different permissions (administrator permissions, moderator permissions, general member permissions, etc.), they can also be recorded through sessions. This part is safer than cookies.
First step, enable Session: session_start()
Before you use session to record user information, you must first use the session_start() function to tell the system to start using it. Please Remember that session_start() must be placed at the top of the web page before anything is output, that is, something like the following. If there is any output before, an error will occur! This is also a problem that most people often encounter.
Open the code page. Step 2: Give the variable value and record it on the server. We set a number variable and gave it a value = 10. Then This number=10 is stored on the server! Basically, the simplest session is set up like this.
The third step is to get the value of session, use $_SESSION["Variable Name"]; before getting the variable value, you must also use the session_star() function first! Then you can echo it directly.
Step 4: Delete session
In fact, the default server will automatically delete sessions that have exceeded the validity period. However, in some cases, it is necessary for users to delete themselves when operating, such as when a member logs out. After active clearing, it will immediately become logged out. At this time, the following two methods can be used to clear it:
unset($_SESSION['变数名称']); session_destroy();
One method is to directly give the variable name and delete the record individually. The second method will clear all sessions.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to clear session in php. For more information, please follow other related articles on the PHP Chinese website!