Search code examples
phpsession-cookiesslimmiddleware

Slim 2: How do I use session cookie in the middleware?


After looking around online, I still don't understand how session works in Slim2. The examples of Slim SessionCookie is extremely rare. Almost none. And that I am stuck with what I can get from the doc.

http://docs.slimframework.com/sessions/cookies/

"The second argument is optional; it is shown here so you can see the default middleware settings. The session cookie middleware will work seamlessly with the $_SESSION superglobal so you can easily migrate to this session storage middleware with zero changes to your application code.

If you use the session cookie middleware, you DO NOT need to start a native PHP session. The $_SESSION superglobal will still be available, and it will be persisted into an HTTP cookie via the middleware layer rather than with PHP’s native session management."

So, for instance,

use Slim\Slim;
use Slim\Middleware\SessionCookie;

$app = new Slim();

$app->add(new SessionCookie(
    array(
        'expires' => '20 minutes',
        'path' => '/',
        'domain' => null,
        'secure' => false,
        'httponly' => false,
        'name' => 'slim_session',
        'secret' => 'CHANGE_ME',
        'cipher' => MCRYPT_RIJNDAEL_256,
        'cipher_mode' => MCRYPT_MODE_CBC
    )
));

$app->get('/admin', function () use ($app) {
    // Check for session.
    if (session: user exist) { 
        echo "Hello Admin";
    } else {
        $app->redirect('login');
    }
});

$app->run();

How can I set session: user to the middleware and retrieve it?

This is how I would do in native PHP,

bootstrap.php

// Check username and password, if they match with the ones in db, 
// then get the hashed key in the user row. 
// Last, store the key in the session.
$_SESSION["user"] = 'hashedkeyxxxx';

admin.php,

// Check if the session exist when the user want to access the admin only pages.
if ($_SESSION["user"]) { 
    echo "Hello Admin";
} else {
    // redirect
}

How can I do this with Slim then?


Solution

  • Taken directly from the documentation.

    "If you use the session cookie middleware, you DO NOT need to start a native PHP session. The $_SESSION superglobal will still be available, and it will be persisted into an HTTP cookie via the middleware layer rather than with PHP’s native session management."

    http://docs.slimframework.com/sessions/cookies/

    So when you initilize the middleware you are abble to access the $_SESSION in the same way as you do in traditional PHP. Happy coding.

    Edit: you are not able to achieve that straight out of the box. But if you use custom middleware like this https://github.com/yusukezzz/slim-session-manager. You will get an API where the usage differs.

    But as copied from the documentation, you are not using the PHP implementation but rather the SLIM implementation that works in a similar way.