简体   繁体   English

在苗条框架中使用`SessionCookie`时,$ _ SESSION不是全局的吗?

[英]$_SESSION is not global when using `SessionCookie` in slim framework?

I found that if I use SessionCookie in slim, $_SESSION cannot be retrieved globally. 我发现如果我苗条地使用SessionCookie ,则无法全局检索$_SESSION

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

function checkAdmin() {
    if ( ! isset($_SESSION['admin']) || $_SESSION['admin'] !== TRUE) {
        exit(NULL);
    }
}

$app->get('/.*', function() use($app) {
    // function checkAdmin() can retrieve the session value I set here
    $_SESSION['admin'] = TRUE;
    $app->render('index.php');
});

$app->post('/loginAdmin', function() use($app) {
    // function checkAdmin() can NOT retrieve the session value I set here
    $_SESSION['admin'] = TRUE;
    exit(TRUE);
});

$app->post('/getAllUsers', 'checkAdmin', function() use($app) {
    // Not related.
});

checkAdmin() will always exit(NULL) if I set $_SESSION in the function assigned to POST /loginAdmin , so it seems that the session assignment didn't work. 如果我在分配给POST /loginAdmin的函数中设置$_SESSION ,则checkAdmin()将始终exit(NULL) ,因此似乎会话分配无效。

But if I set $_SESSION in the function assigned to GET / , checkAdmin can retrieve it everywhere. 但是,如果我在分配给GET /的函数中设置$_SESSION ,则checkAdmin可以在任何地方检索它。

It must be something related to SessionCookie because the native session store works fine. 它必须与SessionCookie有关,因为本机会话存储可以正常工作。

So how can I make it work? 那么我该如何运作呢?

If you use the session cookie middleware, you DO NOT need to start a native PHP session. 如果您使用会话cookie中间件,则无需启动本机PHP会话。 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. $ _SESSION超级全局变量仍然可用,并且将通过中间件层而不是PHP的本机会话管理将其持久化为HTTP cookie。

so don't use session cookie middleware 所以不要使用session cookie middleware

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM