PHP Session
PHP session variables are used to store information about a user session, or to change the settings of a user session. Session variables store information for a single user and are available to all pages in the application.
PHP Session Variables
When you operate an application on your computer, you open it, make some changes, and then close it. This is very much like a conversation (Session). The computer knows who you are. It knows when you open and close the application. However, a problem arises on the Internet: because HTTP addresses cannot maintain state, the web server does not know who you are and what you have done.
PHP session solves this problem by storing user information on the server for later use (such as user name, purchased items, etc.). However, session information is temporary and will be deleted after the user leaves the website. If you need to store information permanently, you can store the data in a database.
The mechanism of a session is: create a unique id (UID) for each visitor and store variables based on this UID. The UID is stored in a cookie, or transmitted via the URL.
Starting a 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:
Example
The code above registers the user's session with the server so that you can start saving user information, and assigns a UID to the user session.
Storing Session Variables
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
Example
Output:
浏览量:1
In the example below, we create a simple page-view counter. The isset() function checks whether the "views" variable has been set. If the "views" variable is set, we increment the counter. If "views" does not exist, we create the "views" variable and set it to 1:
Example
Destroying a Session
If you want to delete some session data, you can use the unset() or session_destroy() functions.
The unset() function is used to free the specified session variable:
Example
You can also completely destroy the session by calling the session_destroy() function:
Example
Note:session_destroy() will reset the session, and you will lose all stored session data.