Slim SessionCookie 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 usual average:

<?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 will not be saved. Also, when I open the list of cookies in the navigator, I can't see. Why is the session cookie not being saved? I have checked and made sure the call()

class function is SessionCookie

executed.

+3


source to share


1 answer


How if you added CustomMiddleware

earlier than Slim\Middleware\SessionCookie

?

Something like that:

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 template file home.php

:

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

      



This works flawlessly for me. But if I add Slim\Middleware\SessionCookie

before mine CustomMiddleware

, the output $_SESSION['test']

remains NULL

.

This is how middleware works:

Middleware

So, your answer will never get any value $_SESSION

since you are calling your $_SESSION

before SessionCookie

.

+3


source







All Articles