Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

session_destroy() after certain amount of time in PHP

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'];

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this should work

<?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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...