php - 我的 Laravel 5.2.10 session 不会持续

标签 php laravel session laravel-5 session-cookies

我有一个全新的 Laravel 5 安装,事实上我已经在多个版本上尝试过这个并且一直遇到同样的问题。

除了将 session 驱动程序设置为 redis 之外,我没有更改任何默认值。 (基于文件也有同样的问题)。

我有两条路由设置如下

Route::get('/set/{value}', function($value) {
    var_dump(Session::getId());
    Session::set('test', $value);
    return view('welcome');
});

Route::get('/get', function() {
    return 'Get ' . Session::get('test');
});

如果我访问 url/set/abc,我会看到 session 出现在 REDIS 中(我还会看到使用基于文件时创建的文件)。 session 在 REDIS 中看起来很好,如下所示

127.0.0.1:6379> KEYS *
 1) "laravel:1a3ae6caff6346e4a173fdc1ab4c6eb0f138806b"
 2) "laravel:fed1af2fb44c6e625953237c3fa6fcbb05366a5c"
 3) "laravel:cb37286ccfe3e7caa20557aca840f50cb5a5f20d"

每次我访问该页面时,它都会重新创建一个新 session 。

session.php文件的主要部分如下:

'lifetime' => 120,

'expire_on_close' => false,

我还在 REDIS 中检查了 session 变量的 TTL,它们确实在 120 分钟(以秒为单位)时被初始化。

知道我做错了什么吗?

可能值得注意的是,我正在使用宅基地虚拟机(完全库存)对此进行测试。我也尝试过使用多个浏览器。没有任何 cookie 被发送到浏览器,我认为 session ID 应该作为初始 get 请求的一部分发送到浏览器?

最佳答案

Laravel 的中间件类 \Illuminate\Session\Middleware\StartSession 负责启动你的 session 。在 L5.2 之前,它会在每个请求上运行,因为它是全局中间件堆栈的一部分。现在,它是可选的,因为 L5.2 希望在同一应用程序中同时使用 Web UI 和 API。

如果打开 app/Http/Kernel.php,您会看到 StartSession 中间件是名为 web。您需要将所有路线放入其中才能使您的示例正常工作。

Route::group(['middleware' => ['web']], function () {
    Route::get('/set/{value}', function($value) {
        var_dump(Session::getId());
        Session::set('test', $value);
        return view('welcome');
    });

    Route::get('/get', function() {
        return 'Get ' . Session::get('test');
    });
});

您可以看到 web 中间件组还负责其他事情,例如在所有 View 上提供 $errors 变量。

您可以在文档中阅读更多相关信息:

By default, the routes.php file contains a single route as well as a route group that applies the web middleware group to all routes it contains. This middleware group provides session state and CSRF protection to routes.

Any routes not placed within the web middleware group will not have access to sessions and CSRF protection, so make sure any routes that need these features are placed within the group. Typically, you will place most of your routes within this group:

来源:https://laravel.com/docs/5.2/routing

关于php - 我的 Laravel 5.2.10 session 不会持续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34958607/

相关文章:

php - 在 laravel 5 的表中显示寄存器数量

java - 当浏览器调用另一台服务器时,Tomcat session 共享不起作用

Laravel Homestead - 页面停止工作 ERR_ADDRESS_UNREACHABLE

c# - 超出 WCF MaxConcurrentSessions

java - 我应该在 Google App Engine 中使用 session 吗?

php - 如果使用 PHP SQL 查询为空,则显示一条消息

php - 无法查询工作

php - 用户和产品之间的多对多关系 - Laravel

javascript - 在不破坏内联 Javascript 的情况下缩小 HTML 代码

php - 如何使用 laravel 在 1 个 View 中显示 2 个表数据?