Slim4 Session data?

Hi guys,

I’m trying to do a redirect but for some reason my session data is missing once redirected?

public function index(Request $request, Response $response)
    {

        $this->flashMessage->addMessageNow('here', 'there');

        $this->view->getEnvironment()->addGlobal('msg', [
            'info' => 'working',
            'warning' => 'wtf'
        ]);

        $_SESSION['user'] = 'here';

       // dump($this->session->get('slimFlash'));

        return $response->withHeader('Location','/about')->withStatus(302);

        //return $this->view->render($response, '/web/web_home.twig');
    }

How does that work? Do i need to make a middleware that saves session data…?

Yes, you need a session middleware that starts the session. Example:

<?php

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class SessionMiddleware implements MiddlewareInterface
{
    /**
     * Invoke middleware.
     *
     * @param ServerRequestInterface $request The request
     * @param RequestHandlerInterface $handler The handler
     *
     * @return ResponseInterface The response
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

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

        session_write_close();

        return $response;
    }
}

Thanks for the feedback I have session_start() on the first line of my boot file so surely that should be enough to maintain session data for a redirect?

Not in every case. Because there are known issues with lost sessions and redirects. If you already put session_start() in your bootstrap file and it still not working then it’s not enough or another (setup) issue? Have you tried to add the middleware?

Hi Odan,

Yes I have but even that doesnt seem to keep the data…

use Slim\Middleware\Session;

// Add Twig-View Middleware
$app->add(TwigMiddleware::createFromContainer($app));

// Register Middleware To Be Executed On All Routes
$app->add('csrf');

$app->add(new Session([
    'name'         => getenv('APP_NAME'),
    'autorefresh'  => getenv('APP_SESSION_AUTOREFTESH'),
    'lifetime'     => getenv('APP_SESSION_LIFETIME'),
    'secure'       => getenv('APP_SESSION_SECURE'),
    'httponly'     => getenv('APP_SESSION_HTTPONLY'),
]));

//$app->add(new FlashMessageMiddleware($container)); #TODO this is giving problems

// The RoutingMiddleware should be added after our CORS middleware so routing is performed first
$app->addRoutingMiddleware();

/*SHOULD BE LAST MIDDLEWARE*/
$app->addErrorMiddleware(getenv('APP_DEBUG'), true, true);

using the “bryanjhv/slim-session”: “^4.0” package

using the “bryanjhv/slim-session”: “^4.0” package

It’s good to know now. The more context, the better we can help. :wink:

Then you already have a session middleware and should let the middleware start the session. You can / should remove your custom session_start() function call in your bootstrap file then. Better let the middleware handle the session start.

But the problem is (maybe) also here.

$this->startSession();

return $handler->handle($request);

I guess you try to redirect before the session is fully saved. Then you have to call session_write_close(); before returning the response. But this middleware doesn’t call it.

I’m starting to think the package is a problem. I commented out all session middleware and just left the session_start() in the boot file and all my data is there…

This whole middleware approach of slim 4 just seems to over complicate everything.

another question the middleware works last in first out but how does that work with before and after…

order
Last in
then before
First out
then after

or

1 Last in
1.1 then before
1.2 then after
2 First out
2.1 then after
2.2 then before

Unfortunately Slim 4 (and 3) middleware stack is LIFO (last in first out) and not FIFO (first in first out). Read my comment about this topic here.

The LIFO aproach is sometimes problematic in case of sessions, CORS and so on. That’s why I would prefer FIFO. But anyway…

You could try this session library: odan/session

Thanks I’ll have a look other wise ill just use normal session for now. :facepunch: