session_destroy() after certain amount of time in PHP

后端 未结 2 1274
闹比i
闹比i 2020-12-11 12:07

I am currently saving a session in my form page:

$testingvalue = "SESSION TEST";

$_SESSION[\'testing\'] = $testingvalue;

相关标签:
2条回答
  • 2020-12-11 12:23

    you need a static start time to expire. $session_life > $inactive will always be greater no matter what.

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

    or session-set-cookie-params

    0 讨论(0)
  • 2020-12-11 12:37

    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
    
    0 讨论(0)
提交回复
热议问题