PHP code example of yiisoft / session

1. Go to this page and download the library: Download yiisoft/session library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yiisoft / session example snippets


use Yiisoft\Router\Group;
use Yiisoft\Session\SessionMiddleware;

return [
    Group::create('/blog')
        ->middleware(SessionMiddleware::class)
        ->routes(
            // ...
        )
];

return [
    Yiisoft\Yii\Http\Application::class => [
        '__construct()' => [
            'dispatcher' => DynamicReference::to(static function (Injector $injector) {
                return ($injector->make(MiddlewareDispatcher::class))
                    ->withMiddlewares(
                        [
                            ErrorCatcher::class,
                            SessionMiddleware::class, // <-- add this
                            CsrfMiddleware::class,
                            Router::class,
                        ]
                    );
            }),
        ],
    ],
];

public function actionProfile(\Yiisoft\Session\SessionInterface $session)
{
    // get a value
    $lastAccessTime = $session->get('lastAccessTime');

    // get all values
    $sessionData = $session->all();
        
    // set a value
    $session->set('lastAccessTime', time());

    // check if value exists
    if ($session->has('lastAccessTime')) {
        // ...    
    }
    
    // remove value
    $session->remove('lastAccessTime');

    // get value and then remove it
    $sessionData = $session->pull('lastAccessTime');

    // clear session data from runtime
    $session->clear();
}

/** @var Yiisoft\Session\Flash\FlashInterface $flash */

// request 1
$flash->set('warning', 'Oh no, not again.');

// request 2
$warning = $flash->get('warning');
if ($warning !== null) {
    // do something with it
}

public function actionProfile(\Yiisoft\Session\SessionInterface $session)
{
    // start session if it's not yet started
    $session->open();

    // work with session

    // write session values and then close it
    $session->close();
}

public function actionProfile(\Yiisoft\Session\SessionInterface $session)
{
    // discard changes and close session
    $session->discard();

    // destroy session completely
    $session->destroy();    
}

$handler = new MySessionHandler();
$session = new \Yiisoft\Session\Session([], $handler);