The examples in this article describe the usage of Session in ThinkPHP. Share it with everyone for your reference. The details are as follows:
The Session class is encapsulated in ThinkPHP and users can use it directly. Commonly used methods are:
Session::set(name, value): Register session.
Session::is_set(name): Check whether the value of Session is set.
Session::get(name): Read session.
Session::clear(): Clear the Session.
Session::destroy(): Destroy session.
ThinkPHP opens the session by default, so there is no need to use the session_start() function to open the session before using the Session class.
Use session instance
Next, register the session by form submission, and read the session value in template mode and Session::get mode in the operation on the other two pages.
Register session
User module sessionTest operation registration session example:
Homepage
Other pages of this module
Logout
testuser Hello! Home Logout
Otherwise the form will be output.
Check whether the session is registered
Detection in template
In the template, you can directly use tags such as present or notempty or even switch to determine whether the session variable is registered to decide whether to output the corresponding session value (directly output the session variable value in the form of an array unit) or display other page elements. Specifically Please refer to the template tag part of this tutorial and the example above.
In-operation detection
In operation, you can use the Session::is_set method to check whether the value of Session is set. For example, the operation of User module user is as follows:
In other pages (such as Index/index), determine and read the session code snippet:
The session may be invalid (cannot be passed to other pages) in ThinkPHP. The possible reasons are as follows:
Use the first letter of the Session class without capital letters, such as: session::set.
The page has information output, such as blank lines in the entry file, etc.
The session storage path (session.save_path) permissions on the server (Linux/Unix) are incorrect, resulting in the failure to store the session information correctly.
Suggestions for scope issues:
ThinkPHP’s Session class is just a simple wrapper for session. In fact, you can directly use PHP’s native session function in the operation. This is also the official recommendation.
I hope this article will be helpful to everyone’s ThinkPHP framework programming.