在 PHP 中经过一定时间后的 session_destroy()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17179249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:26:14  来源:igfitidea点击:

session_destroy() after certain amount of time in PHP

php

提问by Si8

I am currently saving a session in my form page:

我目前正在我的表单页面中保存一个会话:

$testingvalue = "SESSION TEST";

$_SESSION['testing'] = $testingvalue;

$testingvalue = "会话测试";

$_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();

session_destroy();

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

销毁会话。但我想做的是在 2 小时后销毁会话。

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

如果我超过 2 小时没有活动,这应该是空白的?:

echo $_SESSION['testing'];

回声 $_SESSION['测试'];

回答by wardpeet

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

回答by amigura

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

您需要一个静态开始时间才能到期。$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'];

or session-set-cookie-params

session-set-cookie-params