PHP code example of lithemod / session

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

    

lithemod / session example snippets


use function Lithe\Middleware\Session\session;

// Add the middleware to the application
$app->use(session());

$app->use(session([
    'lifetime' => 3600, // 1 hour
    'domain' => 'example.com',
    'secure' => true, // Only over HTTPS
    'httponly' => true, // Accessible only via HTTP
    'samesite' => 'Strict', // SameSite policy
    'path' => 'storage/framework/session', // Path to store sessions
]));

$app->get('/set-user', function ($req, $res) {
    $req->session->put('user', 'John Doe'); // Set the session variable
    return $res->send('User set in the session!');
});

$app->get('/get-user', function ($req, $res) {
    $user = $req->session->get('user', 'User not found'); // Retrieve the session variable
    return $res->send('User: ' . $user);
});

$app->get('/remove-user', function ($req, $res) {
    $req->session->forget('user'); // Remove the session variable
    return $res->send('User removed from the session!');
});

$app->get('/destroy-session', function ($req, $res) {
    $req->session->destroy(); // Destroy all session variables
    return $res->send('All session variables have been destroyed!');
});

$app->get('/check-session', function ($req, $res) {
    $isActive = $req->session->isActive(); // Check if the session is active
    return $res->send('Session active: ' . ($isActive ? 'Yes' : 'No'));
});

$app->get('/regenerate-session', function ($req, $res) {
    $req->session->regenerate(); // Regenerate the session ID
    return $res->send('Session ID regenerated!');
});

$app->get('/session-id', function ($req, $res) {
    $sessionId = $req->session->getId(); // Get the session ID
    return $res->send('Session ID: ' . $sessionId);
});

$app->get('/set-session-id', function ($req, $res) {
    $req->session->setId('newSessionId'); // Set a new ID for the session
    return $res->send('New session ID set!');
});

$app->get('/all-session-data', function ($req, $res) {
    $allSessionData = $req->session->all(); // Get all session variables
    return $res->send('Session data: ' . json_encode($allSessionData));
});

$app->get('/has-user', function ($req, $res) {
    $hasUser = $req->session->has('user'); // Check if the session variable 'user' exists
    return $res->send('User in session: ' . ($hasUser ? 'Yes' : 'No'));
});

  $user = $req->session->user; // Equivalent to $req->session->get('user');
  

  $req->session->user = 'Jane Doe'; // Equivalent to $req->session->put('user', 'Jane Doe');