Laravel页面刷新后会话丢失

8

我有一个关于Laravel中会话的小问题。

我已经制作了身份验证功能,如下所示:

public function postSignin(){
        $attempt = Auth::attempt(array('username' => Input::get('username'), 'password' => Input::get('password')));
        if ($attempt) {
            return Redirect::to('index')->with('message', 'Anda telah login!' . $attempt)
                                        ->with('usersess', Input::get('username'));
        } else if(!$attempt){
                return Redirect::to('auth')
                            ->with('message', 'Kombinasi email/password salah ' . $attempt)
                            ->withInput();
        }
    }

让我们来看一下,我已经将'usersess'变量存入会话中,并在头文件中使用如下代码:{{ Session::get('usersess') }} 并将其放置在头部。
但问题是,当我刷新页面时,会话消失了!有什么线索可以不让会话丢失而把它找回来吗?
我已经学习了PHP并使用<?php session_start() ?>这个基本函数,但是在Laravel中它是如何工作的呢?
谢谢!
更新我的session.php配置。

return array(

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "array"
|
*/

'driver' => 'file',

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => 180,

'expire_on_close' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/

'files' => storage_path().'/sessions',

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

'connection' => null,

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => array(2, 100),

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/

'cookie' => 'invsess',

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/

'domain' => null,

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => false,

 );


你能发布你的 app/config/session.php 文件吗? - Laurence
@TheShiftExchange请查看更新的部分。顺便说一下,我将刀片放入了两个不同的页面。其中索引扩展了标题。我将会话放在标题刀片中,但我的路由将转到Index刀片。有问题吗? - randytan
你不应该在代码中的任何地方放置session_start() - Laravel会为你处理所有的session包装。 - Laurence
@TheShiftExchange,RMcLeod已经给出了解决方案。谢谢你的帮助! :) - randytan
6个回答

12

->with将数据暂时存储到会话中,仅在该页面加载期间有效。如果您想在会话中保留项目,请使用Session::put('key', 'value')。因此,对于您的示例:

if($attempt) {
    Session::put('usersess', Input::get('username'));
    return Redirect::to('index')->with('message', 'Anda telah login!' . $attempt);
}

编辑

您可以使用Session::get('key')来检索值,或者使用Session::pull('key')返回该值并遗忘该值。 您也可以使用Session::forget('key')来删除项目。 Session::flush()清除会话中的所有内容。

会话文档可以在此处找到。


那么,当我想要删除会话时,是使用Auth::logout();还是使用Session::flush();? - randytan
然后我会使用flush for logout方法 :) 感谢您的帮助! - randytan

8
这个问题发生在我使用时。
use Illuminate\Support\Facades\Session;

你可以使用“

”代替它。
use Symfony\Component\HttpFoundation\Session\Session;

"并且:"
//to set a session variable use
$session = new Session();
$session->set('variableName', $requestData['key']);

//to get that session variable
$session = new Session();
$session->get('variableName');

谢谢,我的情况是由于一个dd()导致请求无法完成,从而无法存储会话:请参见这里 - T30

5

我想为这个问题做出贡献,因为我遇到了同样的问题,但我的解决方案与获得赞同的解决方案不同。

在我将项目放入会话中后,它们似乎在下一次页面加载时消失了。

我这样做的方式是通过 AJAX 调用。每当我执行 AJAX 调用时,我总是在最后使用 exit,以防止任何不必要的页面处理。我发现这个 exit 阻止了 Laravel 进一步进行并将数据写入永久会话中。

Star Fox voice:祝你好运!


2
谢谢,我一直在使用“dd()”进行测试,没有想到会出现这个问题。 - plexus
1
我不确定我浪费了多少时间来调试 dd()var_dump()+exit 的问题,直到我看到这个评论并意识到我正在破坏会话本身。非常感谢! - valkirilov

3

显然这不是你的问题,但对于其他找到这个问题而接受的答案无法解决问题的人来说,可能会有帮助:

如果您将Laravel会话存储在数据库中,则该会话值的大小存在限制。 Laravel会话迁移具有名为“payload”的字段,其为文本类型。 如果超过该字段的限制,整个会话将被终止。 我在向我的会话动态添加JSON模型数据时遇到了此问题。

Schema::create('sessions', function (Blueprint $table) {
    $table->string('id')->unique();
    $table->text('payload');
    $table->integer('last_activity');
});

How much UTF-8 text fits in a MySQL "Text" field?


2

还有一件事,你必须永远记住。 如果你的页面中有任何种类的退出语句,那么会话将不会被设置。这可能是在您的会话设置语句之后。它可以是停止页面的任何代码。例如,在您的页面中调用了EXIT函数或dd()函数。


0

检查一下你的 .js 文件中是否没有删除 cookies。这是导致我的问题的原因:

var now = new Date();
now.setTime(now.getTime()+(-1*24*60*60*1000));
var expires = "=;"+" path=/; expires="+now.toUTCString();
document.cookie = "lastpage"+expires;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接