Session


Does not support operating the $_SESSION array, only the Session class can be used.

The Session class of 6.0 can well support environments such as Swoole/Workerman.

Open Session

Session function is not enabled by default. If you need to use Seesion, you need to add the following middleware definition to the global middleware definition file:

'think\middleware\SessionInit'

If it is multi-application mode and you only use it for some applications, you can also enable it separately in the application middleware definition file.

Session initialization

The system will automatically initialize the Session according to the parameters configured in session.php.

The session setting parameters supported by default include:

Parameter Description
typesession type
storeSpecify the storage identifier when type is set to cache type
expiresession expiration time (seconds) must be greater than 0
var_session_idRequest session_id variable name
namesession_name
prefixsession prefix
serializeSerialization method

You can directly call the relevant methods of the Session class without any operation, for example:

Session::set('name', 'thinkphp');
Session::get('name');

Serialization

The session data will be automatically serialized when it is saved. , and automatically deserialize when reading. You can customize the serialization mechanism.

For example, set it to use JSON serialization in the configuration file:

'serialize'    =>    ['json_encode', 'json_decode'],

Try to avoid saving objects to the Session

Basic usage

Assignment

Session::set('name', 'thinkphp');
// 支持两级赋值
Session::set('user.name', 'thinkphp');

Judge whether it exists

Session::has('name');
Session::has('user.name');

Get the value

// 如果值不存在,返回null
Session::get('name');
// 如果值不存在,返回空字符串
Session::get('name', '');
// 支持多级
Session::get('user.name');

Delete

Session::delete('name');

Get the value and delete

// 取值并删除
Session::pull('name');

If the value of name does not exist, Null is returned.

Clear

Session::clear();

Flash data is valid before the next request

// 设置session 并且在下一次请求之前有效
Session::flash('name','value');

Clear the valid data for the current request in advance

// 清除当前请求有效的session
Session::flush();

Note that Session writes The data input operation will be stored locally when the request ends, so do not use exit and other interrupt operations after writing the Session data, which may cause the Session to not be written normally.

Multi-level array

Support multi-level array operations of session, for example:

// 赋值(当前作用域)
Session::set('name.item','thinkphp');
// 判断(当前作用域)是否赋值
Session::has('name.item');
// 取值(当前作用域)
Session::get('name.item');
// 删除(当前作用域)
Session::delete('name.item');

The set and delete methods can only support two-level arrays, Other methods support arbitrary levels of array operations.

Assistant function

The system also provides the assistant function session to complete the same function, for example:

// 赋值
session('name', 'thinkphp');

// 判断是否赋值
session('?name');

// 取值
session('name');

// 删除
session('name', null);

// 清除session
session(null);

Read the Session in the Request object

Session data can be read in the Request object (setting is not supported)

public function index(Request $request) {
    // 读取某个session数据
    $request->session('user.name', '');
    // 获取全部session数据
    $request->session();
}

But the Session write operation is not supported in the Request class.

Application Independent Session

If the default file type is used, the Session saving path of multiple applications is the same, which means that the session is shared between multiple applications. For data, if you do not want to share session data, you can set a different path or a different prefix for each application.

If it is a File type, the default session data is saved in the runtime/session directory. You can set path to change the storage path.

If it is a driver of other types, you can set the prefix configuration parameter to distinguish different application session data.

Session driver

The default Session driver uses file cache recording and supports the following configuration

##gc_probabilityGC recycling Probabilitygc_maxlifetimeGC recycling maximum lifetime

In addition to file types, other Session types can also be supported, for example:

return [
    'type'       => 'redis',
    'prefix'     => 'think',
    'auto_start' => true,
     // redis主机
    'host'       => '127.0.0.1',
     // redis端口
    'port'       => 6379,
     // 密码
    'password'   => '',
]

indicates using redis as the session type.

For the above configuration to take effect, please ensure that the redis cache configuration has been added to the stores in the cache configuration file cache.php, for example:

return [
    'default'    =>    'file',
    'stores'    =>    [
        // 文件缓存
        'file'   =>  [
            // 驱动方式
            'type'   => 'file',
            // 设置不同的缓存保存目录
            'path'   => '../runtime/file/',
        ],  
        // redis缓存
        'redis'   =>  [
            // 驱动方式
            'type'   => 'redis',
            // 服务器地址
            'host'       => '127.0.0.1',
        ],  
    ],
];

The currently built-in supported types include redis, memcache and memcached.

Customized driver

If you need to customize the Session driver, your driver class must implement the think\contract\SessionHandlerInterface interface, which contains three methods.

interface SessionHandlerInterface
{
    public function read(string $sessionId): string;
    public function delete(string $sessionId): bool;
    public function write(string $sessionId, string $data): bool;
}

The read method is executed when Session::start() is called, and will only be executed once.
The write method is executed when localizing session data (calling the Session::save() method), and the system will automatically execute it at the end of each request.
The delete method is executed when the session is destroyed (calling the Session::destroy() method).


parameters Description
pathsession save path
data_compressWhether to compress data
gc_divisorGC recycling probability