2

How can you set up php session variable to be destroyed after let's say hour? I was searching web but I found very different opinions and non of them was helping much.Thank you...

like let's say I have two variables

$_SESSION["loged"];
$_SESSION["user"];

And I want them to be still there after browser is closed for 2 more hours.

Jakub Zak
  • 1,212
  • 6
  • 32
  • 53
  • 1
    possible duplicate of http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes – summea Mar 22 '12 at 22:36

3 Answers3

0

You could set a session variable that holds the time when the session was created:

In this example the session destroys after 10 seconds:

<?php
session_start();

if (!$_SESSION['created_at']) {
    $_SESSION['created_at']=time();
}

$age=time()-$_SESSION['created_at'];

if ($age>10) {
    session_destroy();
}

echo $age;
?>
stewe
  • 41,820
  • 13
  • 79
  • 75
0

If you want to control the lifetime of a particular session variable, you will need to roll your own timeout check. The best way to do that is to add a function to your library where you can specify how long a particular variable is valid for. This puts both pieces of information into an array you put in the session. Then, in your common included code, do a loop through that array and unset() all expired session variables. Make sure the session itself can last as long as the highest value you want to use.

PHP Sessions in and of themselves don't have a hard lifetime value. They have a garbage collector which expires sessions. The setting session.gc_maxlifetime is the maximum age beyond which the garbage collector will delete the session. Note that this maximum age refers to when it was last accessed, not created.

However, there is also session.gc_probability and session.gc_divisor which together tell PHP how often to run the garbage collector. The normal settings mean about 1 in every 100 session starts will run the garbage collector. But this means that if you have a very low volume site, it is possible the garbage collector may not run for many hours. The visible effect of this is that the sessions seem to last way beyond the session.gc_maxlifetime setting.

staticsan
  • 29,935
  • 4
  • 60
  • 73
0

Some users may want to modify this using the settings in ini ie

ini_set('session.gc_maxlifetime') 

but this is the WRONG approach! You will be modifying the configuration of your entire PHP deployment. This is impractical and dangerous, and shouldn't be used for a simple case like this. Not to mention, most shared hosting plans disable ini_set because the changes would affect every user on the system.

Instead, here is some boilerplate code to handle session expiration manually.

//Initially

   session_start();
    $date = new DateTime();
    $ts = $date->getTimestamp();
    if($ts - $_SESSION["timestamp"]) > 60*60) {
    session_destroy();
    //log out!}
    else{
    $_SESSION["timestamp"] = $ts;
    }
stan
  • 4,885
  • 5
  • 49
  • 72