Zach P
Zach P

Reputation: 570

Expire php session variable after period of time

Is there a way to set a php session variable ($_SESSION['example') to expire after a given amount of time. To clarify, I want to keep the user's session intact and keep all other variables with their values, I only want to set a single session variable to expire after a short time period (1 minute or so). Is there any way to set the variable to expire on its own or will I have to keep track of time and delete the variable when I have determined that the time has expired? I am using php 5 with apache2 on ubuntu. Thanks.

Upvotes: 3

Views: 2366

Answers (1)

apokryfos
apokryfos

Reputation: 40653

Maybe do something like :

$_SESSION['example'] = $value;
$_SESSION['expiries']["example"] = time() + 30*60; // 30 mins

Declare function:

function expireSessionKeys() {
     foreach ($_SESSION["expiries"] as $key => $value) {
          if (time() > $value) { 
             unset($_SESSION[$key]);
          }
     }
}

Then wherever you have session_start() follow it up with exprireSessionKeys()

All this can be built in a custom session handler

Upvotes: 7

Related Questions