php 用户登录后 Laravel 5 会话不持久

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30769434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:03:25  来源:igfitidea点击:

Laravel 5 session not persisting after user is logged in

phpsessionlaravel

提问by Andrei

I'm having an interesting issue with Laravel 5.

我在 Laravel 5 上遇到了一个有趣的问题。

After logging in a user, the logged in status is not persisted across pages. Clearly it has something to do with Session::.

用户登录后,登录状态不会跨页面持久化。显然与Session::.

The way I'm logging in a user is pretty straight-forward:

我登录用户的方式非常简单:

if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']],
    isset($data['remember_me']) ? TRUE : FALSE))
{
    return redirect()->intended('/');
}

A simple print_r(Session::all());gives me the following if the user is NOT logged in:

print_r(Session::all());如果用户未登录,一个简单的给我以下内容:

Array
(
    [_token] => wV8o75lZnCZ0f6CMMQgdBBM2AxSYjtWisAXx6TgZ
    [flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [_previous] => Array
        (
            [url] => http://localhost/public
        )

)

After the user is logged in an redirected to /the array looks like this:

用户登录后重定向到/数组如下所示:

Array
(
    [_token] => wV8o75lZnCZ0f6CMMQgdBBM2AxSYjtWisAXx6TgZ
    [flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [_previous] => Array
        (
            [url] => http://localhost/public/
        )

    [login_82e5d2c56bdd0811318f0cf078b78bfc] => 2
)

However, after any action that will lead to a page refresh or a redirect, the session status is lost.

但是,在任何会导致页面刷新或重定向的操作之后,会话状态将丢失。

My config/session.phpfile looks like so:

我的config/session.php文件看起来像这样:

<?php

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'lottery' => [2, 100],
    'cookie' => 'laravel_session',
    'path' => '/',
    'domain' => null,
    'secure' => false,

];

The locally stored file for the session can be written and read.

可以写入和读取会话的本地存储文件。

I've tried using databasedrive instead of file. Same thing happens the [login_xx] => 2key/value is lost and I'm logged out.

我试过使用database驱动器而不是文件。同样的事情发生了,[login_xx] => 2键/值丢失了,我退出了。

Since the Session::is not completely reset I'm suspecting that I'm not logging in the user properly or simply doing something that I shouldn't be doing somewhere.

由于Session::未完全重置,我怀疑我没有正确登录用户或只是在做一些我不应该在某处做的事情。

回答by Kalpesh Panchal

I faced similar issue, I simply called:

我遇到了类似的问题,我只是打电话给:

Session::save();

after any add/update/delete to Session storage. So it looked like:

在对会话存储进行任何添加/更新/删除之后。所以它看起来像:

$id = Input::get('id');
Session::forget('cart.' .$id);
Session::save();

回答by spedley

I had the same issue. Once I removed the various combinations of dd() and print_r() I was using to dump responses for testing purposes and allowed the method to complete and fully render the view, the issue went away and sessions persisted.

我遇到过同样的问题。一旦我删除了 dd() 和 print_r() 的各种组合,我用来转储响应以进行测试并允许该方法完成并完全呈现视图,问题就消失了,会话仍然存在。

回答by Ernesto Hernández

I solved changing

我解决了改变

'cookie' => 'laravel_session',

to

'cookie' => 'myapp_session',

according to laravel the name of the cookie affects every driver

根据 Laravel,cookie 的名称会影响每个驱动程序

回答by tbutcaru

I'm not familiar with Laravel, but on CodeIgniter I save user session in CI's Session Class and Laravel has one too.

我不熟悉 Laravel,但在 CodeIgniter 上,我将用户会话保存在 CI 的会话类中,而 Laravel 也有一个。

I suggest to use the build-in sessionwhich is more persistent than default $_SESSION - probably it saves user data in database and on each page refresh/change the session is populated again from DB.

我建议使用比默认 $_SESSION 更持久的内置会话- 可能它将用户数据保存在数据库中,并且在每次刷新/更改页面时,会话都会从数据库中再次填充。

When user authenticates, just save its session data like this:

当用户进行身份验证时,只需像这样保存其会话数据:

Session::put('userData', 'value');

...where value could be just a boolean value or an entire object that holds user specific data.

...其中 value 可能只是一个布尔值或包含用户特定数据的整个对象。

On each page load, get user data from session:

在每个页面加载时,从会话中获取用户数据:

$user = Session::get('userData');

if($user->id) echo 'user is logged-in'; //or if($user) - depends on what you store in 'userData' key
else echo 'guest only privilegies';

EDIT:I see that you use the Auth Class. My answer is mostly for manual login of the user and it works.
I think that the Auth Class should be doing this by default, but probably you're missing some configuration or there's a bug.

编辑:我看到您使用了 Auth 类。我的回答主要是针对用户的手动登录,并且可以正常工作。
我认为 Auth 类应该默认执行此操作,但可能您缺少某些配置或存在错误。

Here's a possible solution (Laravel 4, but it worths a try): http://laravel.io/forum/11-11-2014-authcheck-always-returning-false

这是一个可能的解决方案(Laravel 4,但值得一试):http://laravel.io/forum/11-11-2014-authcheck-always-returning-false

Update:

更新:

As of thisyou should try to change the driver value from

由于这个你应该尝试改变从驾驶员值

'driver' => env('SESSION_DRIVER', 'file')

to

'driver' => 'file'

...also on Laravel's docs you can see that the driver has to be defined like that.

...也在 Laravel 的文档中,您可以看到必须像这样定义驱动程序。

回答by Y M

You need to make sure of 2 things if you are using default laravel's file sessionwhich you can check if you are using in session.php file.

如果您使用默认的 Laravel文件会话,您需要确保两件事,您可以检查是否在 session.php 文件中使用。

  1. The session directory ie storage/framework/session/ is writable.
  2. The routes for logging in maybe (/login) and for checking authentication (maybe /dashboard) are all within the group web
  1. 会话目录即 storage/framework/session/ 是可写的。
  2. 登录可能(/login)和检查认证(可能/dashboard)的路由都在组web中

ie.

IE。

Route::group(['middleware' => ['web']], function () {
   Route::get('/home/login', ['as' => 'login', 'uses' => 'HomeController@getLogin']);
Route::post('/home/login', ['as' => 'login', 'uses' => 'HomeController@postLogin']);
   Route::get('/home/dashboard', ['as' => 'home', 'uses' => 'HomeController@getDashboard']);
}

This worked for me in Laravel 5.

这在 Laravel 5 中对我有用。

回答by Rob_vH

First, make sure you don't have some sort of a before filter, middleware, or route group that is causing them to be logged out. At least temporarily, search for any Auth::logout() and comment it out. I have seen this be the problem more than once.

首先,确保您没有某种导致它们被注销的前置过滤器、中间件或路由组。至少暂时搜索任何 Auth::logout() 并将其注释掉。我不止一次看到这是问题所在。

Second, you look like you're doing this call correctly. The third parameter is $login : bool and it defaults to true. This is not your problem, but please change your TRUE and FALSE to true and false to meet with PSR-1/2 standards.

其次,您看起来正确地进行了此调用。第三个参数是 $login : bool ,它默认为 true。这不是您的问题,但请将您的 TRUE 和 FALSE 更改为 true 和 false 以满足 PSR-1/2 标准。

I would have advised that you try another driver, but you have done that and have the same result. This leads me to think that you have some sort of earlier code that is misdirecting to a logout().

我会建议您尝试另一个驱动程序,但您已经这样做了并得到了相同的结果。这让我认为您有某种早期的代码被误导到 logout()。

回答by iipavlov

Make sure that the target route also uses the middleware StartSession. In my "fresh" installation of Laravel 5.2 the "web" middleware group uses it, but the root path (/), which also happens to be the default $redirectTo after login, was outside of it. Huge loss of time.

确保目标路由也使用中间件 StartSession。在我“全新”安装的 Laravel 5.2 中,“web”中间件组使用它,但根路径 (/),也恰好是登录后的默认 $redirectTo,不在它的范围内。时间损失巨大。

回答by roll

I had this problem to and i solve this way. After Auth::attempor Auth::login()dont use echo, var_dump or dd()i dont know why but those prevent to keep the session in the browser.

我有这个问题,我以这种方式解决。在使用Auth::attempAuth::login()不使用之后,echo, var_dump or dd()我不知道为什么,但那些阻止将会话保留在浏览器中。

And now is working

现在正在工作

                public function testLogin(Request $request, $id){

                    $user = Account::find($id);
                    Auth::login($user);

                }

回答by ShuifuraX

correctedHum... Ensure your machine is setted with good date and hour, and equally the other machines on the network who working with.

更正Hum... 确保您的机器设置了正确的日期和时间,以及网络上与之合作的其他机器。

For exemple in Debian system:

以 Debian 系统为例:

In the command prompt, hit date(you will see the date), if it's not correct follow these instructions:

在命令提示符下,点击date您将看到日期),如果不正确,请按照以下说明操作:

  1. apt-get install ntp
  2. service ntp start
  3. date (normally the date and hour are corrected)
  1. apt-get 安装 ntp
  2. 服务 ntp 启动
  3. 日期(通常更正日期和小时)

回答by namal

Use "cookie" driver instead of "file" of session.php (config\session.php\driver). I had a problem with login using "Auth::loginUsingId()" api instead of "Auth::attempt()" api, it destroyed the session for another request.

使用“cookie”驱动程序而不是 session.php (config\session.php\driver) 的“文件”。我在使用“Auth::loginUsingId()”api而不是“Auth::attempt()”api登录时遇到问题,它破坏了另一个请求的会话。