PHP code example of responsive-sk / slim4-session

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

    

responsive-sk / slim4-session example snippets


use ResponsiveSk\Slim4Session\SessionFactory;

// Create session manager
$session = SessionFactory::create();

// Start session
$session->start();

// Set data
$session->set('user_id', 123);
$session->set('username', 'john_doe');

// Get data
$userId = $session->get('user_id');
$username = $session->get('username', 'guest');

// Check if key exists
if ($session->has('user_id')) {
    echo 'User is logged in';
}

// Flash messages
$session->flash('success', 'Login successful!');
$message = $session->getFlashMessage('success');

// Advanced flash usage
$flash = $session->getFlash();
$flash->add('error', 'Something went wrong');
$errors = $flash->consume('error'); // Get and clear

// Session management
$sessionId = $session->getId();
$session->regenerateId();
$session->destroy();

// Production (secure settings)
$session = SessionFactory::createForProduction([
    'name' => 'my_app_session',
    'cache_expire' => 180,
]);

// Development (relaxed settings)
$session = SessionFactory::createForDevelopment([
    'name' => 'dev_session',
]);

// Testing (no cookies)
$session = SessionFactory::createForTesting();

$session = SessionFactory::create([
    'name' => 'custom_session',
    'cookie_lifetime' => 3600,
    'cookie_secure' => true,
    'cookie_httponly' => true,
    'cookie_samesite' => 'Strict',
]);

interface SessionInterface extends \Countable, \IteratorAggregate
{
    // Core session methods
    public function set(string $key, mixed $value): void;
    public function get(string $key, mixed $default = null): mixed;
    public function remove(string $key): void;
    public function has(string $key): bool;
    public function all(): array;
    public function clear(): void;

    // Session lifecycle
    public function isStarted(): bool;
    public function start(): bool;
    public function destroy(): bool;

    // Session ID management
    public function getId(): ?string;
    public function regenerateId(): bool;
    public function getName(): string;
    public function setName(string $name): void;

    // Flash messages
    public function flash(string $key, mixed $value): void;
    public function getFlash(): FlashInterface;
    public function getFlashMessage(string $key, mixed $default = null): mixed;
    public function hasFlash(string $key): bool;
}

SessionFactory::create()                    // Default config
SessionFactory::createForProduction()      // Production config
SessionFactory::createForDevelopment()     // Development config
SessionFactory::createForTesting()         // Testing config
SessionFactory::createWithConfig()         // Custom config

$session = SessionFactory::createForProduction([
    'cookie_secure' => true,        // HTTPS only
    'cookie_httponly' => true,      // No JavaScript access
    'cookie_samesite' => 'Strict',  // CSRF protection
    'use_strict_mode' => true,      // Session fixation protection
]);

// Create test session (no cookies)
$session = SessionFactory::createForTesting();

// Test session functionality
$session->set('test_key', 'test_value');
$this->assertEquals('test_value', $session->get('test_key'));

use ResponsiveSk\Slim4Session\SessionFactory;
use ResponsiveSk\Slim4Session\SessionInterface;

return [
    SessionInterface::class => function () {
        return SessionFactory::createForProduction();
    },
];

use ResponsiveSk\Slim4Session\SessionInterface;

class SessionMiddleware
{
    public function __construct(
        private readonly SessionInterface $session
    ) {}
    
    public function __invoke(Request $request, RequestHandler $handler): Response
    {
        if (!$this->session->isStarted()) {
            $this->session->start();
        }
        
        return $handler->handle($request);
    }
}

/** @var SessionInterface $session */
$session = SessionFactory::create();

// Type-safe operations
$userId = $session->get('user_id', 0);        // mixed
$username = $session->get('username', '');     // mixed
$data = $session->all();                       // array<string, mixed>
$hasKey = $session->has('key');                // bool