Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Reset session lifetime on reload

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?

like image 865
user3205494 Avatar asked Dec 13 '15 15:12

user3205494


2 Answers

$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.

like image 112
Emrah Tuncel Avatar answered Oct 18 '22 07:10

Emrah Tuncel


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

like image 21
Armen Avatar answered Oct 18 '22 06:10

Armen