Webman Session Management

Example

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        $name = $request->get('name');
        $session = $request->session();
        $session->set('name', $name);
        return response('hello ' . $session->get('name'));
    }
}

You can obtain an instance of Workerman\Protocols\Http\Session through $request->session(); and use the methods of the instance to add, modify, or delete session data.

Note: The session object automatically saves session data when it is destroyed, so do not store the object returned by $request->session() in a global array or class member, which would prevent the session from being saved.

Get All Session Data

$session = $request->session();
$all = $session->all();

It returns an array. If there is no session data, it returns an empty array.

Get a Value from the Session

$session = $request->session();
$name = $session->get('name');

If the data does not exist, it returns null.

You can also pass a default value as the second parameter to the get method; if the corresponding value is not found in the session array, it will return the default value. For example:

$session = $request->session();
$name = $session->get('name', 'tom');

Store Session

Use the set method to store a single piece of data.

$session = $request->session();
$session->set('name', 'tom');

set does not have a return value; the session will be automatically saved when the session object is destroyed.

When storing multiple values, use the put method.

$session = $request->session();
$session->put(['name' => 'tom', 'age' => 12]);

Similarly, put does not have a return value.

Delete Session Data

Use the forget method to delete a specific piece or multiple pieces of session data.

$session = $request->session();
// Delete one item
$session->forget('name');
// Delete multiple items
$session->forget(['name', 'age']);

Additionally, the system provides the delete method, which differs from forget in that delete can only delete one item.

$session = $request->session();
// Equivalent to $session->forget('name');
$session->delete('name');

Get and Delete a Value from the Session

$session = $request->session();
$name = $session->pull('name');

The effect is the same as the code below:

$session = $request->session();
$value = $session->get($name);
$session->delete($name);

If the corresponding session does not exist, it returns null.

Delete All Session Data

$request->session()->flush();

It does not return a value; the session will be automatically deleted from storage when the session object is destroyed.

Check if Corresponding Session Data Exists

$session = $request->session();
$has = $session->has('name');

The above will return false if the corresponding session does not exist or if the corresponding session value is null; otherwise, it returns true.

$session = $request->session();
$has = $session->exists('name');

The above code is also used to check whether session data exists; the difference is that when the corresponding session item value is null, it also returns true.

Helper Function session()

Webman provides a helper function session() to achieve the same functionality.

// Get session instance
$session = session();
// Equivalent to
$session = $request->session();

// Get a specific value
$value = session('key', 'default');
// Equivalent to
$value = session()->get('key', 'default');
// Equivalent to
$value = $request->session()->get('key', 'default');

// Assign values to session
session(['key1'=>'value1', 'key2' => 'value2']);
// Equivalent to
session()->put(['key1'=>'value1', 'key2' => 'value2']);
// Equivalent to
$request->session()->put(['key1'=>'value1', 'key2' => 'value2']);

Configuration File

The session configuration file is located in config/session.php, with content similar to the following:

use Webman\Session\FileSessionHandler;
use Webman\Session\RedisSessionHandler;
use Webman\Session\RedisClusterSessionHandler;

return [
    // FileSessionHandler::class or RedisSessionHandler::class or RedisClusterSessionHandler::class 
    'handler' => FileSessionHandler::class,

    // When handler is FileSessionHandler::class, the value is file,
    // When handler is RedisSessionHandler::class, the value is redis
    // When handler is RedisClusterSessionHandler::class, the value is redis_cluster which means redis cluster
    'type'    => 'file',

    // Different handlers use different configurations
    'config' => [
        // Configuration when type is file
        'file' => [
            'save_path' => runtime_path() . '/sessions',
        ],
        // Configuration when type is redis
        'redis' => [
            'host'      => '127.0.0.1',
            'port'      => 6379,
            'auth'      => '',
            'timeout'   => 2,
            'database'  => '',
            'prefix'    => 'redis_session_',
        ],
        'redis_cluster' => [
            'host'    => ['127.0.0.1:7000', '127.0.0.1:7001', '127.0.0.1:7001'],
            'timeout' => 2,
            'auth'    => '',
            'prefix'  => 'redis_session_',
        ]

    ],

    'session_name' => 'PHPSID', // Cookie name for storing session_id
    'auto_update_timestamp' => false,  // Whether to automatically refresh session, default is off
    'lifetime' => 7*24*60*60,          // Session expiration time
    'cookie_lifetime' => 365*24*60*60, // Cookie expiration time for storing session_id
    'cookie_path' => '/',              // Path for storing session_id cookie
    'domain' => '',                    // Domain for storing session_id cookie
    'http_only' => true,               // Whether to enable httpOnly, default is on
    'secure' => false,                 // Whether to enable session only under https, default is off
    'same_site' => '',                 // To prevent CSRF attacks and user tracking, optional values are strict/lax/none
    'gc_probability' => [1, 1000],     // Probability of session garbage collection
];

Security Related

When using sessions, it is not recommended to directly store instances of class objects, especially instances of classes from uncontrollable sources, as deserialization may pose potential risks.