PHP: Reset session lifetime on reload
Asked Answered
T

2

14

This probably is a rather simple question. I have found dozens of similar ones, asking how to generally shorten or extend the session life time in PHP. I know how to achieve that, my PHP script reads like this:

ini_set('session.gc_maxlifetime', 3600);
session_set_cookie_params(3600);
session_start();

This sets my sessions to time out after 3600 seconds. And this basically is what happens, when I initally open a website where I have to log in, I can work with it for exactly one hour, then all session data is being deleted and I need to log in again.

However, this is not the behavior I'd expect. I want my Sessions to time out after one hour of inactivity. So when I first open my website at 10:00 am, do something until 10:45, then it should time out at 11:45, not at 11:00 as it does now.

Any suggestions how to achieve this?

Twelfth answered 13/12, 2015 at 15:3 Comment(1)
Well you need to use sessions for this task aswell. You could just update the cookie on pageload in your template. If the last pageload is older than 3600s you will destroy the session. But as you see it has its downsides (needs to be executed every time)Jone
U
31

Use instead of session_set_cookie_params -> setcookie

instead

session_set_cookie_params(3600);
session_start();

use this and call it on every page of your website

$lifetime=3600;
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);

it will update session cookie expiration date on each execution till time()+$lifetime date

Unlive answered 13/12, 2015 at 15:37 Comment(0)
B
2
$lifetime=3600;
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);

Two cookies with the same name are sent with this code and it does not seem appropriate to use.

If you don't want to send session cookies with the same name twice, you can use this code in the cleanest way.

$sessionId = $_COOKIE[session_name()] ?? null;
if($sessionId){ session_id($sessionId); }
session_start(['cookie_lifetime' => 3600]);

The session duration is updated for each request.

Bahner answered 11/1, 2022 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.