Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slim SessionCookie middleware not working

This is my index.php

<?php
$app = new \Slim\Slim(
    array(
        'templates.path' => dirname(__FILE__).'/templates'
    )
);

// Add session cookie middle-ware. Shouldn't this create a cookie?
$app->add(new \Slim\Middleware\SessionCookie());

// Add a custom middle-ware
$app->add(new \CustomMiddleware());

$app->get(
    '/', 
    function () use ($app) {
        $app->render('Home.php');
    }
);

$app->run();
?>

This is my custom middle-ware:

<?php
class CustomMiddleware extends \Slim\Middleware {
    public function call() {
        // This session variable should be saved
        $_SESSION['test'] = 'Hello!';

        $this->next->call();
    }
}
?>

And this is my template (Home.php)

<?php
var_dump($_SESSION['test']);
?>

which will output NULL, so the session variable is not saved. Also, when opening the cookies list in the navigator I don't see any. Why isn't the cookie of the session saved? I verified and made sure that the call() function of the SessionCookie class is executed.

like image 486
ali Avatar asked Jan 25 '26 00:01

ali


1 Answers

How if you add your CustomMiddleware first before Slim\Middleware\SessionCookie?

Something like this:

require 'Slim/Slim.php';

Slim\Slim::registerAutoloader();

class CustomMiddleware extends Slim\Middleware
{
    public function call() {
        // This session variable should be saved
        $_SESSION['test'] = 'Hello!';

        $this->next->call();
    }
}

$app = new Slim\Slim();

$app->add(new CustomMiddleware());

$app->add(new Slim\Middleware\SessionCookie());

// GET route
$app->get('/', function () use ($app)
{
    $app->render('home.php');
});

$app->run();

And your home.php template file:

<?php echo($_SESSION['test']); ?>

For me, it works flawlessly. But if I add Slim\Middleware\SessionCookie before my CustomMiddleware, the output of $_SESSION['test'] remains NULL.

This is how middleware works:

Middleware

So, your response will never get any $_SESSION value, since you set your $_SESSION before SessionCookie called.

like image 153
krisanalfa Avatar answered Jan 26 '26 15:01

krisanalfa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!