Home >Backend Development >PHP Tutorial >PHP session management_Session session
Session starts from the user accessing the page and ends when the user disconnects from the website, forming the life cycle of the Session. Every time a user connects, PHP will automatically generate a unique SessionID to identify the current user and distinguish it from other users.
During the session, PHP generates an identifier named PHPSESSIONID by default (the name can be changed in the php.ini file), which is sent to the browser with each page, and then returned to the web server with the next page request .
SessionID can be saved to the database as session information, used as a primary key to distinguish different users, or used as a unique string in the session file name on the server side.
During a Session, the SessionID will be saved in two locations: the client side and the server side. On the client side, a temporary cookie is used and stored in the specified directory of the browser (called a Session Cookie); on the server side, it is saved in the specified Session directory in the form of a text file.
Create a session through the session_start()
function
bool session_start(void);
Note: There must be no output from the browser before using session_start()
, otherwise an error will occur.
Create a session through the session_register()
function
session_register()
function is used to log a variable for the session to implicitly start the session, but requires the option of the php.ini file to set the register_globals directive If 'on', restart the Apache server.
After the session variables are started, they are all saved in the global array $_SESSION[]
. Creating a session variable via the global array $_SESSION
is easy, just add an element directly to the array.
Session in PHP is powerful: it can save specific data and related information of the current user. Any data type such as array, object, or string can be saved. To add various types of data to the Session, the global array $_SESSION[]
must be applied.
Delete a single session
Deleting session variables is the same as the operation of arrays, just log out directly from an element of the $_SESSION
array.
unset($_SESSION[‘what’]);
Delete multiple sessions
To log out all session variables at once, you can assign an empty array to $_SESSION
$_SESSION = array();
End the current session
If the entire session has ended, you should first log out all session variables, then use the session_destroy()
function to clear the current session, clear all resources in the session, and completely destroy the Session.
session_destroy();
The biggest difference is:
The above introduces the PHP session management_Session session, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.