PHP code example of snicco / session

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

    

snicco / session example snippets


use Snicco\Component\Session\ValueObject\SessionConfig;

$configuration = new SessionConfig([
    // The path were the session cookie will be available
    'path' => '/',
    // The session cookie name
    'cookie_name' => 'my_app_sessions',
    // This should practically never be set to false
    'http_only' => true,
    // This should practically never be set to false
    'secure' => true,
    // one of "Lax"|"Strict"|"None"
    'same_site' => 'Lax',
    // A session with inactivity greater than the idle_timeout will be regenerated and flushed
    'idle_timeout_in_sec' => 60 * 15,
    // Rotate session ids periodically
    'rotation_interval_in_sec' => 60 * 10,
    // Setting this value to NULL will make the session a "browser session".
    // Setting this to any positive integer will mean that the session will be regenerated and flushed
    // independently of activity.
    'absolute_lifetime_in_sec' => null,
    // The percentage that any given call to SessionManager::gc() will trigger garbage collection
    // of inactive sessions.
    'garbage_collection_percentage' => 2,
]);


use Snicco\Component\Session\SessionManager\SessionManger;

$configuration = /* */
$serializer = /* */
$driver = /* */

$session_manger = new SessionManger($configuration, $driver, $serializer);

use Snicco\Component\Session\SessionManager\SessionManger;
use Snicco\Component\Session\ValueObject\CookiePool;

$configuration = /* */
$serializer = /* */
$driver = /* */

$session_manger = new SessionManger($configuration, $driver, $serializer);

// using $_COOKIE
$cookie_pool = CookiePool::fromSuperGlobals();

// or any array.
$cookie_pool = new CookiePool($psr7_request->getCookieParams());


$session = $session_manger->start($cookie_pool);

use Snicco\Component\Session\ImmutableSession;
use Snicco\Component\Session\Session;
use Snicco\Component\Session\ValueObject\ReadOnlySession;

/**
* @var Session $session 
*/
$session = $session_manger->start($cookie_pool);

// You can either rely on type-hints or transform $session to an immutable object like so:
$read_only_session = ReadOnlySession::fromSession($session);

function readFromSession(ImmutableSession $session) {
    
    $session->id(); // instance of SessionId
    
    $session->isNew(); // true/false
        
    $session->userId(); // int|string|null
        
    $session->createdAt(); // timestamp. Can never be changed.
        
    $session->lastRotation(); // timestamp
    
    $session->lastActivity(); // last activity is updated each time a session is saved.
    
    $session->has('foo'); // true/false
    
    $session->boolean('wants_beta_features'); // true/false
    
    $session->only(['foo', 'bar']); // only get keys "foo" and "bar"
    
    $session->get('foo', 'default'); // get key "foo" with optional default value
    
    $session->all(); // Returns array of all user provided data.
    
    $session->oldInput('username', ''); // Old input is flushed after saving a session twice.
    
    $session->hasOldInput('username'); // true/false
    
    $session->missing(['foo', 'bar']); // Returns true if all the given keys are not in the session.
    
    $session->missing(['foo', 'bar']); // Returns true if all the given keys are in the session.
    
}

use Snicco\Component\Session\MutableSession;
use Snicco\Component\Session\Session;
use Snicco\Component\Session\ValueObject\ReadOnlySession;

/**
* @var Session $session 
*/
$session = $session_manger->start($cookie_pool);

function modifySession(MutableSession $session) {
    
    // Store the current user after authentication.
    $session->setUserId('user-1');
    // can be int|string
    $session->setUserId(1);
    
    // Rotates the session id and flushes all data.
    $session->invalidate();
        
    // Rotates the session id WITHOUT flushing data.
    $session->rotate(); 
        
    $session->put('foo', 'bar');
    $session->put(['foo' => 'bar', 'baz' => 'biz']);
        
    $session->putIfMissing('foo', 'bar');
    
    $session->increment('views');
    $session->increment('views', 2); // Increment by 2
    
    $session->decrement('views');
    $session->decrement('views', 2); // Decrement by 2
    
    $session->push('viewed_pages', 'foo-page'); // Push a value onto an array.
    
    $session->remove('foo');
    
    $session->flash('account_created', 'Your account was created'); // account_created is only available during the current request and the next request.
    
    $session->flashNow('account_created', 'Your account was created' ); // account_created is only available during the current request.
    
    $session->flashInput('login_form.email', '[email protected]'); // This value is available during the current request and the next request.

    $session->reflash(); // Reflash all flash data for one more request.
    
    $session->keep(['account_created']); // Keep account created for one more request.
    
    $session->flush(); // Empty the session data.
    
}

$session->put([
    'foo' => [
        'bar' => 'baz'
    ]   
]);

var_dump($session->get('foo.bar')); // baz

// POST request: 

// create user account and redirect to success page.

$session->flash('account_created', 'Great! Your account was created.');

// session is saved.

// GET request:

echo $session->get('account_created');

// session is saved again, account_created is now gone.

// POST request: 

$username = $_POST['username'];

// validate the request...

// Validation failed.
$session->flashInput('username', $username);

// session is saved.

// GET request:

if($session->hasOldInput('username')) {
    $username = $session->oldInput('username');
    // Use username to populate the form values again.
}

// session is saved again, username is now gone.

use Snicco\Component\Session\Driver\EncryptedDriver;
use Snicco\Component\Session\SessionEncryptor;

final class DefuseSessionEncryptor implements SessionEncryptor
{
    private string $key;

    public function __construct(string $key)
    {
        $this->$key = $key;
    }

    public function encrypt(string $data): string
    {
        return Defuse\Crypto\Crypto::encrypt($data, $this->key);
    }

    public function decrypt(string $data): string
    {
       return Defuse\Crypto\Crypto::decrypt($data, $this->key);
    }
}

$driver = new EncryptedDriver(
    $inner_driver,
    new DefuseSessionEncryptor($your_key)
)

use Snicco\Component\Session\SessionManager\SessionManger;
use Snicco\Component\Session\ValueObject\CookiePool;

$configuration = /* */
$serializer = /* */
$driver = /* */
$cookie_pool = /* */;

$session_manger = new SessionManger($configuration, $driver, $serializer);

$session = $session_manger->start($cookie_pool);

$session->put('foo', 'bar');

$session_manger->save($session);

// This will throw an exception.
$session->put('foo', 'baz');


use Snicco\Component\Session\SessionManager\SessionManger;
use Snicco\Component\Session\ValueObject\CookiePool;

$configuration = /* */
$serializer = /* */
$driver = /* */
$cookie_pool = /* */;

$session_manger = new SessionManger($configuration, $driver, $serializer);

$session = $session_manger->start($cookie_pool);

$session->put('foo', 'bar');

$session_manger->save($session);

$cookie = $session_manger->toCookie($session);

$same_site = $cookie->sameSite();
$same_site = ('None; Secure' === $same_site) ? 'None' : $same_site;

setcookie($cookie->name(), $cookie->value(), [
    'expires' => $cookie->expiryTimestamp(),
    'samesite' => $same_site,
    'secure' => $cookie->secureOnly(),
    'path' => $cookie->path(),
    'httponly' => $cookie->httpOnly(),
]);

use Snicco\Component\Session\Driver\InMemoryDriver;

// The in memory driver implements UserSessionDriver
$in_memory_driver = new InMemoryDriver();

// Destroy all sessions, for all users.
$in_memory_driver->destroyAllForAllUsers();

// Destroys all sessions where the user id has been set to (int) 12.
// Useful for "log me out everywhere" functionality.
$in_memory_driver->destroyAllForUserId(12);

$session_selector = $session->id()->selector();
// Destroys all sessions for user 12 expect the passed one.
// Useful for "log me out everywhere else" functionality.
$in_memory_driver->destroyAllForUserIdExcept($session_selector, 12);

// Returns an array of SerializedSessions for user 12.
$in_memory_driver->getAllForUserId(12);

// That's it, this will remove all idle sessions with the percentage that you configured.
$session_manager->gc();