PHP code example of ddrv / slim-session

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

    

ddrv / slim-session example snippets


     

    $storage = new Ddrv\Slim\Session\Storage\FileStorage('/path/to/sessions', 'sess_id');
    $handler = new Ddrv\Slim\Session\Handler($storage);
    

    /** @var Ddrv\Slim\Session\Handler $handler */
    $sessionId = array_key_exists('sess_id', $_COOKIE) ? $_COOKIE['sess_id'] : $handler->generateId(); 
    $session = $handler->read($sessionId);

    // some logic
    
    // When you need to update session ID do
    $session->regenerate();
    
    // some logic

    if ($session->isNeedRegenerate()) {
        $handler->destroy($sessionId);
        $sessionId = $handler->generateId();
    }

    $handler->write($sessionId, $session); // store data to storage and close session
    // add session cookie to response
    setcookie('sess_id', $sessionId, time() + 86400, '/', '.example.com', false, true);
    

    /** @var string $sessionId */
    /** @var Ddrv\Slim\Session\Handler $handler */
    $handler->destroy($sessionId);
    setcookie('sess_id', "", time() + 86400, '/', '.example.com', false, true);
    

/** @var Ddrv\Slim\Session\Session $session */
$session->set('key1', 'value');
$session->set('key2', ['a', 'b', 'c']);
$value = $session->get('key1'); // 'value'
$value = $session->get('key1', 'default'); // 'value'
$value = $session->get('nonexistent-key'); // null
$value = $session->get('nonexistent-key', 'default'); // 'default'

/** @var Ddrv\Slim\Session\Session $session */
$session->flash('key1', 'value'); // 'key1' will be stored only for the current and the next request

// Current request
$session->has('key1');          // true
$value = $session->get('key1'); // 'value'

// Next request
$session->has('key1');          // true
$value = $session->get('key1'); // 'value'

// Other request
$session->has('key1');          // false
$value = $session->get('key1'); // null

/** @var Ddrv\Slim\Session\Session $session */
$session->increment('counter_1'); // 1
$session->increment('counter_1'); // 2
$session->increment('counter_1'); // 3
$session->increment('counter_1'); // 4
$session->increment('counter_1'); // 5
$session->decrement('counter_1'); // 4
$session->decrement('counter_1'); // 3
$session->decrement('counter_1'); // 2
$session->counter('counter_1');   // 2
$session->reset('counter_1');     // 0
$session->counter('counter_1');   // 0

/** @var Ddrv\Slim\Session\Handler $handler */
$handler->removeExpiredSessions(); // Delete sessions not used during the day  

/** @var Ddrv\Slim\Session\Storage $handler */
$cryptHandler = new Ddrv\Slim\Session\Storage\EncryptedStorageDecorator($handler, 'secret-key', 16);