PHP code example of ujjwal / psr7-http-session

1. Go to this page and download the library: Download ujjwal/psr7-http-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/ */

    

ujjwal / psr7-http-session example snippets


$sessionOptions = [
    'name' => 'session_id',
    'sid_length' => 40,
    'cookie' => [
        'domain' => 'your-app.com',
    ]
];

$sessionHandler = new Ojhaujjwal\Session\Handler\FileHandler('path/to/session-data');
$sessionManager = new Ojhaujjwal\Session\SessionManager(
    $sessionHandler,
    $request,
    $sessionOptions
);
$storage = $sessionManager->getStorage();

$sessionManager->start();

// you can manipulate $storage just like $_SESSION   
$storage['some_key'] = 'some_value';
$someKey = $storage['some_key'];

$response = $sessionManager->close($response);
//return the response the the client

$sessionManager = new Ojhaujjwal\Session\SessionManager(
    $sessionHandler,
    $request,
    $sessionOptions
);

$sessionManager->start();

$sessionManager->isStarted(); // returns true

$sessionManager->getId(); //returns alphanumeric string

$sessionManager->regenerate();

$sessionManager->regenerate(false); // does not destroy old session

$response = $sessionManager->close($response);

$storage = $sessionManager->getStorage();

$storage->abcd = 'efgh';
//or
$storage['abcd'] = 'efgh';
//or
$storage->set('abcd', 'efgh');

$abcd =  $storage->abc;
//or
$abcd = $storage['abcd'];
//or
$abcd = $storage->get('abcd');

unset($storage->abc);
//or
unset($storage['abcd']);
//or
$storage->remove('abcd');

$storage->flush();

 $middleware = new Ojhaujjwal\Session\SessionMiddleware($handler, $sessionOptions);
 $middleware->process($request, $delegate);
 // or
 $middleware($request, $response, $next);
 
 //using with zend-expressive
 //after errorhandler and before the routing middleware
 $app->pipe(\Ojhaujjwal\Session\SessionMiddleware::class);