1

I am currently saving a session in my form page:

$testingvalue = "SESSION TEST";

$_SESSION['testing'] = $testingvalue;

On another page I am calling the session to use the value:

<?php
session_start(); // make sure there is a session

echo $_SESSION['testing']; //prints SESSION TEST???
?>

Now I want to use the

session_destroy();

to destroy the session. But what I would like to do is destroy the session after 2 hours have been passed.

Any idea on how to do it and also where should I put it?

I have something like this:

 <?php
session_start();

// 2 hours in seconds
$inactive = 7200; 

$session_life = time() - $_session['testing'];

if($session_life > $inactive)
{  
 session_destroy(); 
}

$_session['testing']=time();
    
    echo $_SESSION['testing']; //prints NOTHING?
    ?>

Will that work?

If I am inactive for more than 2 hours this should be blank?:

echo $_SESSION['testing'];

4

2 回答 2

6

像这样的东西应该工作

<?php
// 2 hours in seconds
$inactive = 7200; 
ini_set('session.gc_maxlifetime', $inactive); // set the session max lifetime to 2 hours

session_start();

if (isset($_SESSION['testing']) && (time() - $_SESSION['testing'] > $inactive)) {
    // last request was more than 2 hours ago
    session_unset();     // unset $_SESSION variable for this page
    session_destroy();   // destroy session data
}
$_SESSION['testing'] = time(); // Update session
于 2013-06-18T21:39:58.223 回答
2

您需要一个静态开始时间才能过期。$session_life > $inactive无论如何都会更大。

session_start();

$testingvalue = "SESSION TEST";
$_SESSION['testing'] = $testingvalue;

// 2 hours in seconds
$inactive = 7200;


$_SESSION['expire'] = time() + $inactive; // static expire


if(time() > $_SESSION['expire'])
{  
$_SESSION['testing'] = '';
 session_unset();
 session_destroy(); 
$_SESSION['testing'] = '2 hours expired'; // test message
}

echo $_SESSION['testing'];

session-set-cookie-params

于 2013-06-18T21:40:46.943 回答