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.
Asked
Active
Viewed 2,042 times
3

Zach P
- 560
- 10
- 30
-
1It is not a duplicate. I specifically asked to keep the session alive along with all other session variables while only deleting a single variable. – Zach P Jul 08 '16 at 15:29
-
You could achieve this with cookies... not sure if that's the direction you want to go – Dylan Wheeler Jul 08 '16 at 15:31
-
Maybe look into using some sort of memory cache (like Redis) as a means to achieve the expiration effect. – apokryfos Jul 08 '16 at 15:32
-
You can store a expiry date in your session and clean the variable if the expiry date is in the past. There is an example of code here: http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes/1270960#1270960 – A.L Jul 08 '16 at 15:32
-
1Actually, you only need to determine if it has expired when it is used. So keep a time of 'last access' against it. When it is accessed then check the `last access time`. Delete it if it is too old. i.e. return nothing. – Ryan Vincent Jul 08 '16 at 15:35
1 Answers
7
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

apokryfos
- 38,771
- 9
- 70
- 114
-
Thanks. Very useful to implement when need to show messages on a refreshed page. – Bogdan C Apr 29 '20 at 17:25