PHP Sessions expiry time - keeping session alive f

2020-02-12 06:09发布

问题:

I have a site that creates a Session for shopping carts.

$_SESSION['cart']=array();

It seems as if the server automatically kills the session after X time of inactivity, I assume this is set in php.ini (but my host does not grant me access, they just let me tell them the changes, so I cannot play around! :().

Is there a better way to keep the sessions alive for example for 2 days or for a specific number of minutes/hours?

回答1:

Call session_set_cookie_params() before you call session_start() in your scripts:

$session_lifetime = 3600 * 24 * 2; // 2 days
session_set_cookie_params ($session_lifetime);
session_start();
// ...

From the documentation:

session_set_cookie_params()
Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.

Alternatively, you could update your php.ini file's session.cookie_lifetime directive to 2 days (in seconds).



回答2:

set a cookie and change in you config that the session use cookies

session_start();
set_cookie("PHPSESSID", session_id(), time() + 3600 * 2);

this keep alive your session for 2 hours