如何在Laravel中设置会话超时时间?

35

是否有内置的方法来设置会话在一定时间后过期。我的当前设置似乎在30分钟后过期,我希望禁用它或至少增加它,但我找不到在Laravel中可以设置它的任何地方?

5个回答

63

app/config/session.php中,您有:

lifetime选项,它允许您设置会话过期时间,以分钟为单位(而不是秒)。

'lifetime' => 60,

意味着会话将在一小时后过期。

这里还有一个设置:

'expire_on_close' => true,

该设置决定当浏览器关闭时会话是否过期。

你可能也会对其他设置感兴趣,比如 php.ini 值:

session.cookie_lifetime = 0

session.gc_maxlifetime = 1440

这些是默认值。

第一个选项表示会话 cookie 存储的时间长度 - 默认值为 0(浏览器关闭后失效)。第二个选项表示在多少后 PHP 可以销毁此会话数据。

我说“可以”是因为还有另一个选项 session.gc_probabilityphp.ini 文件中,它决定了运行垃圾回收器的概率。默认情况下,在 1440 秒(24 分钟)后,只有 1% 的几率会销毁此会话数据。


4
这段话的前半部分(关于lifetime和expire_on_close)是正确的,后面的部分不正确。 - Rob Grant
我该如何在Laravel 6中添加60秒的会话超时呢? - Meher Ullah Khan Raj

29

检查你的php.ini文件,它有一个session.gc_maxlifetime(还有session.cookie_lifetime)的值,用于设置PHP允许会话持续时间的限制。当Laravel设置选项时,它将cookie_lifetime作为app/config/session.php中设置的值传递。

然而,在最大生存期到达后,会话并不会立即过期。发生的是:在该时间段过去后,垃圾收集器才可以删除该会话。

解决问题的方法

一种解决方法是检查你的php.ini文件。你可能已经定义了此变量:session.gc_maxlifetime。默认情况下,它设置为1440。 只需注释或删除它

从此时起,你的会话可能会使用你的session.php配置值正常工作。


12

自Laravel 4.1起,已停用原生的PHP会话支持

要配置会话存活时间,请编辑app/config/session.php文件并设置以下内容:

/* if this is set to 'native' it will use file.
   if this is set to 'array' sessions will not persist across requests
   effectively expiring them immediately.
*/ 
'driver' => 'file'

/* number of minutes after which the session is available for Laravel's
   built in garbage collection.
   Prior to 4.1 you could set this to zero to expire sessions when
   the browser closes. See the next option below.
*/
'lifetime' => 60

/* If true sessions will expire when the user closes the browser.
   This effectively ignores your lifetime setting above.
   Set to false if you want Laravel to respect the lifetime value.
   If your config file was written before 4.1 you need to add this.
*/
'expire_on_close' => false,

参考资料:

在命令行中运行artisan changes 4.1.*以查看有关native会话驱动程序相当于file的说明。

$ artisan changes 4.1.* | grep -i native
-> Native session driver has been replaced by 'file'. Specifying 'native' driver will just use the new file driver.

5

App\Config\Session.php

检查生命周期...

您还可以设置...

Cookie::make('name', 'value', 60); // 1 hr

0
你也可以在`.env`文件中处理这个表单。
在`.env`文件中,`SESSION_LIFETIME=120`。

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