在 slim 框架中使用 `SessionCookie` 时 $_SESSION 不是全局的?
$_SESSION is not global when using `SessionCookie` in slim framework?
我发现如果我在slim中使用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.
});
如果我在分配给 POST /loginAdmin
的函数中设置 $_SESSION
,checkAdmin()
将始终 exit(NULL)
,因此会话分配似乎不起作用。
但是如果我在分配给GET /
的函数中设置$_SESSION
,checkAdmin
就可以到处检索它。
它一定与 SessionCookie
有关,因为本机会话存储工作正常。
那么我怎样才能让它发挥作用呢?
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.
所以不要使用 session cookie middleware
我发现如果我在slim中使用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.
});
如果我在分配给 POST /loginAdmin
的函数中设置 $_SESSION
,checkAdmin()
将始终 exit(NULL)
,因此会话分配似乎不起作用。
但是如果我在分配给GET /
的函数中设置$_SESSION
,checkAdmin
就可以到处检索它。
它一定与 SessionCookie
有关,因为本机会话存储工作正常。
那么我怎样才能让它发挥作用呢?
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.
所以不要使用 session cookie middleware