如何在PHP中创建持久会话? [英] How do I create persistent sessions in PHP?

查看:64
本文介绍了如何在PHP中创建持久会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用session_start()在PHP中启动会话,但是当我的浏览器关闭时,该会话消失了.

I used session_start() to initiate a session in PHP, but when my browser closes, the session is gone.

如何使用PHP创建在浏览器关闭期间持续存在的持久会话?

How do I use PHP to create persistent sessions that last across browser closes?

推荐答案

请参见php.ini默认值0表示在浏览器关闭时结束会话.

The default value of 0 means to end the session when the browser closes.

您可以直接在php.ini中覆盖此值,也可以在使用 ini_set 启动会话之前在应用程序中对其进行设置.将其设置为大于0的值将使会话在该持续时间内存活.

You can override this value either directly in php.ini or set it in your application prior to starting the session using ini_set. Setting it to something greater than 0 will cause the session to live for that duration.

例如

ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);  // 7 day cookie lifetime
session_start();

上面的示例将会话cookie设置为从会话开始时起7天.

The above example causes the session cookie to be set with an expiration of 7 days from when the session is started.

注意::如果您从同一段代码开始所有网页的会话,则每次调用session_start()时,会话都不会继续延长. cookie生存期是从第一次启动会话时开始设置的,而不是在后续请求时开始.如果要将会话的生存期从当前时间延长7天,请参见 session_regenerate_id().

Note: If you start your session for all of your webpages from the same piece of code, this will not continue to extend the session expiration each time session_start() gets called. The cookie lifetime is set from when the session is first started, not on subsequent requests. If you want to extend the lifetime of a session out 7 days from the current time, see also session_regenerate_id().

也请注意:如果您的会话.gc_maxlifetime 值设置为小于会话cookie长度的值,您可能会遇到以下情况:用户5天未访问该网站,并且当他们返回时,会话cookie不再有效,因为服务器上的数据已被删除.为了解决这个问题,您还应该将此会话数据的生存期设置为至少与cookie生存期一样长.如手册所述,可能需要对要保留的会话数据使用自定义session.save_path的时间长于默认值.因此,您的脚本可能如下所示:

Also Note: If your session.gc_maxlifetime value is set to something less than the length of the session cookie, you can have a situation where the user does not visit the site for 5 days and when they return, the session cookie is no longer valid because the data on the server has been deleted. To remedy this, you should also set the lifetime for this session data to be at least as long as your cookie lifetime. As the manual states, it may be necessary to use a custom session.save_path for the session data you want to persist longer than the default. Therefore, your script may look like this:

ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);
ini_set('session.gc_maxlifetime', 60 * 60 * 24 * 7);
ini_set('session.save_path', '/home/yoursite/sessions');
session_start();

这篇关于如何在PHP中创建持久会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆