PHP development basic tutorial - Session
1. Introduction to PHP Session
Through the study in the previous section, we know that Cookie maintains data with the server by saving data on the client. Connected, and Session maintains the connection by saving data on the server side.
PHP session variables are used to store information about the user session (session), or to change the settings of the user session (session). Session variables store information for a single user and are available to all pages in the application.
2. PHP Session Variables
When we operate an application on the computer, you open it and make changes. , and then close it. It's a lot like a conversation. The computer knows who you are. It knows when you open and close apps. However, on the Internet a problem arises: since HTTP addresses cannot maintain state, the web server has no idea who you are and what you do.
PHP session solves this problem by storing user information on the server for subsequent use (such as user name, purchased items, etc.). However, session information is temporary and will be deleted after the user leaves the site. If you need to store information permanently, you can store the data in a database.
Session works by creating a unique id (UID) for each visitor and storing variables based on this UID. The UID is stored in a cookie or passed through the URL.
##3. Start PHP Session
Before you store user information in a PHP session, you must first start the session. Note: The session_start() function must be placed before the tag:The above code will register the user's session with the server so that you can start saving user information, and at the same time, it will User sessions are assigned a UID.
4. Storing Session Variables
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: Example: The code is as followsThe output is as shown on the right In the following example, we create a simple page-view counter. The isset() function detects whether the "views" variable has been set. If the "views" variable is set, we increment the counter. If "views" does not exist, create the "views" variable and set it to 1: The code is as follows The output is as shown on the right Every time it is refreshed, the number of views increases by onephp中文网(php.cn)
##5. Destroy SessionIf we want to delete some session data, we can use the unset() or session_destroy() function.
The unset() function is used to release the specified session variable:
我们也可以通过调用 session_destroy() 函数彻底销毁 session:Note: session_destroy() will reset the session and you will lose all stored session data.
Note: The difference between cookie and session