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 about a single user and are available to all pages in an application.
PHP Session Variables
When you work with an application on your computer, you open it, make changes, and then close it. This is very much like a 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 or what you have done.
PHP sessions solve this problem by storing user information on the server for later use (such as username, purchased items, etc.). However, session information is temporary and is deleted after the user leaves the website. If you need to store information permanently, you can store the data in a database.
The working mechanism of sessions is: a unique id (UID) is created for each visitor, and variables are stored based on this UID. The UID is stored in a cookie, or transmitted via the URL.
Start 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 <html> tag:
Example
The above code registers the user's session with the server, allowing you to start saving user information, and also assigns a UID to the user session.
Store 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
Destroy Session
If you wish to delete some session data, you can use the unset() or session_destroy() function.
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
Other ExtensionsNote:session_destroy() will reset the session, and you will lose all stored session data.