PHP code example of tobento / service-session

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

    

tobento / service-session example snippets


use Tobento\Service\Session\Session;
use Tobento\Service\Session\SessionInterface;
use Tobento\Service\Session\SaveHandlerInterface;
use Tobento\Service\Session\ValidationInterface;

$session = new Session(
    name: 'sess',
    maxlifetime: 1800,
    cookiePath: '/',
    cookieDomain: '',
    cookieSamesite: 'Strict',
    secure: true,
    httpOnly: true,
    saveHandler: null, // null|SaveHandlerInterface
    validation: null, // null|ValidationInterface
);

var_dump($session instanceof SessionInterface);
// bool(true)

use Tobento\Service\Session\SessionFactory;
use Tobento\Service\Session\SessionFactoryInterface;
use Tobento\Service\Session\SessionInterface;
use Tobento\Service\Session\SaveHandlerInterface;
use Tobento\Service\Session\ValidationInterface;

$sessionFactory = new SessionFactory();

$session = $sessionFactory->createSession('name', [
    'maxlifetime' => 1800,
    'cookiePath' => '/',
    'cookieDomain' => '',
    'cookieSamesite' => 'Strict',
    'secure' => true,
    'httpOnly' => true,
    'saveHandler' => null, // null|SaveHandlerInterface
    'validation' => null, // null|ValidationInterface
]);

var_dump($session instanceof SessionInterface);
// bool(true)

use Tobento\Service\Session\PdoMySqlSaveHandler;
use Tobento\Service\Session\SaveHandlerInterface;
use PDO;

$pdo = new PDO(
    dsn: 'mysql:host=localhost;dbname=db_name',
    username: 'root',
    password: '',
    options: [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false,
    ],
);

$saveHandler = new PdoMySqlSaveHandler(
    table: 'session',
    pdo: $pdo
);

var_dump($saveHandler instanceof SaveHandlerInterface);
// bool(true)

use Tobento\Service\Session\NullSaveHandler;
use Tobento\Service\Session\SaveHandlerInterface;

$saveHandler = new NullSaveHandler();

var_dump($saveHandler instanceof SaveHandlerInterface);
// bool(true)

use Tobento\Service\Session\RemoteAddrValidation;
use Tobento\Service\Session\ValidationInterface;

$remoteAddr = $_SERVER['REMOTE_ADDR'] ?? null;

// PSR-7
// $remoteAddr = $serverRequest->getServerParams()['REMOTE_ADDR'] ?? null;

$validation = new RemoteAddrValidation(
    remoteAddr: $remoteAddr,
    trustedProxies: ['192.168.1.1'], // or null
    remoteAddrKey: '_session_remoteAddr', // is default
);

var_dump($validation instanceof ValidationInterface);
// bool(true)

var_dump($validation->remoteAddr());
// string(9) "127.0.0.1"

var_dump($validation->trustedProxies());
// array(1) { [0]=> string(11) "192.168.1.1" }

use Tobento\Service\Session\HttpUserAgentValidation;
use Tobento\Service\Session\ValidationInterface;

$validation = new HttpUserAgentValidation(
    httpUserAgent: $_SERVER['HTTP_USER_AGENT'] ?? null,
    httpUserAgentKey: '_session_httpUserAgent' // default
);

var_dump($validation instanceof ValidationInterface);
// bool(true)

var_dump($validation->httpUserAgent());
// string(78) "Mozilla/5.0 ..."

use Tobento\Service\Session\Validations;
use Tobento\Service\Session\RemoteAddrValidation;
use Tobento\Service\Session\HttpUserAgentValidation;
use Tobento\Service\Session\ValidationInterface;

$validation = new Validations(
    new RemoteAddrValidation($_SERVER['REMOTE_ADDR'] ?? null),
    new HttpUserAgentValidation($_SERVER['HTTP_USER_AGENT'] ?? null),
);

var_dump($validation instanceof ValidationInterface);
// bool(true)

$validations = $validation->validations();
// array<int, ValidationInterface>

use Tobento\Service\Session\ValidationInterface;
use Tobento\Service\Session\SessionInterface;
use Tobento\Service\Session\SessionValidationException;

/**
 * ValidationInterface
 */
interface ValidationInterface
{
    /**
     * Process the validation.
     *
     * @param SessionInterface $session
     * @return void
     * @throws SessionValidationException
     */
    public function process(SessionInterface $session): void;
}

use Tobento\Service\Session\SessionStartException;
use Tobento\Service\Session\SessionExpiredException;
use Tobento\Service\Session\SessionValidationException;

try {
    $session->start();
} catch (SessionStartException $e) {
    // handle
} catch (SessionExpiredException $e) {
    $session->destroy();
    
    // You might to restart session and regenerate id
    // on the current request.
    $session->start();
    $session->regenerateId();
    
    // Or you might send a message to the user instead.
    
} catch (SessionValidationException $e) {
    // handle
}

$session->set('key', 'value');

// using dot notation:
$session->set('meta.color', 'color');

$value = $session->get('key');

// using dot notation:
$value = $session->get('meta.color');

// using a default value if key does not exist
$value = $session->get('key', 'default');

$has = $session->has('key');

// using dot notation:
$has = $session->has('meta.color');

// using multiple keys.
$has = $session->has('key', 'meta.color');

$has = $session->has(['key', 'meta.color']);

$session->delete('key');

// using dot notation:
$session->delete('meta.color');

$session->deleteAll();

$data = $session->all();

$session->flash('key', 'value');

// using dot notation:
$session->flash('message.success', 'Message');

$session->now('key', 'value');

// using dot notation:
$session->now('message.success', 'Message');

$session->once('key', 'value');

// using dot notation:
$session->once('message.success', 'Message');

$session->regenerateId();

$session->destroy();

$name = $session->name();

$id = $session->id();

use Tobento\Service\Session\SessionSaveException;

try {
    $session->save();
} catch (SessionSaveException $e) {
    // handle
}

use Tobento\Service\Middleware\MiddlewareDispatcher;
use Tobento\Service\Middleware\AutowiringMiddlewareFactory;
use Tobento\Service\Middleware\FallbackHandler;
use Tobento\Service\Container\Container;
use Tobento\Service\Session\Session;
use Tobento\Service\Session\SessionInterface;
use Tobento\Service\Session\Middleware\Session as SessionMiddleware;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Nyholm\Psr7\Factory\Psr17Factory;

// create middleware dispatcher.
$dispatcher = new MiddlewareDispatcher(
    new FallbackHandler((new Psr17Factory())->createResponse(404)),
    new AutowiringMiddlewareFactory(new Container()) // any PSR-11 container
);

$session = new Session(
    name: 'sess',
    maxlifetime: 1800,
    cookiePath: '/',
    cookieDomain: '',
    cookieSamesite: 'Strict',
    secure: true,
    httpOnly: true,
    saveHandler: null,
    validation: null,
);

$dispatcher->add(function(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
    
    $session = $request->getAttribute(SessionInterface::class);
    
    var_dump($session instanceof SessionInterface);
    // bool(false)
    
    return $handler->handle($request);
});

$dispatcher->add(new SessionMiddleware($session));

$dispatcher->add(function(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
    
    $session = $request->getAttribute(SessionInterface::class);
    
    var_dump($session instanceof SessionInterface);
    // bool(true)
    
    return $handler->handle($request);
});

$request = (new Psr17Factory())->createServerRequest('GET', 'https://example.com');

$response = $dispatcher->handle($request);