How do you manage and handle sessions in Slim Framework?

How do you manage and handle sessions in Slim Framework?

To manage and handle sessions in Slim Framework, follow these steps:

1. Start PHP Sessions

In your index.php or bootstrap file, enable PHP sessions using session_start() at the beginning of the file:

Example

<?php
session_start();
?>

2. Set Session Data

In your Slim route or middleware, you can set session variables using the $_SESSION superglobal:

Example

<?php
$app->get('/set-session', function ($request, $response, $args) {
    $_SESSION['user'] = 'John Doe';
    return $response->write('Session data set');
});
?>

3. Get Session Data

To retrieve session data in your routes, use $_SESSION:

Example

<?php
$app->get('/get-session', function ($request, $response, $args) {
    $user = $_SESSION['user'] ?? 'Guest';
    return $response->write("Hello, $user");
});
?>

4. Destroy Sessions

To log out or clear session data, use session_unset() and session_destroy():

Example

<?php
$app->get('/destroy-session', function ($request, $response, $args) {
    session_unset();
    session_destroy();
    return $response->write('Session destroyed');
});
?>

5. Middleware for Sessions (Optional)

You can also create a middleware to ensure that sessions are available for every route:

Example

<?php
$sessionMiddleware = function ($request, $handler) {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    return $handler->handle($request);
};

$app->add($sessionMiddleware);
?>

Related Questions & Topics

Powered and designed by igetvapeaustore.com | © 2024 codestap.com.