如何在30分钟后使PHP会话到期?

Tom*_*Tom 1017 php cookies session

我需要让会话保持30分钟,然后将其销毁.

Gum*_*mbo 1623

您应该实现自己的会话超时.其他人提到的两个选项(session.gc_maxlifetimesession.cookie_lifetime)都不可靠.我会解释原因.

第一:

session.gc_maxlifetime
session.gc_maxlifetime指定数据被视为"垃圾"并清理的秒数.在会话开始期间发生垃圾收集.

但垃圾收集器只是以session.gc_probability除以session.gc_divisor的概率开始.并使用这些选项的默认值(分别为1和100),机率仅为1%.

好吧,您可以简单地调整这些值,以便更频繁地启动垃圾收集器.但是当垃圾收集器启动时,它将检查每个注册会话的有效性.这是成本密集型的​​.

此外,使用PHP的默认session.save_handler文件时,会话数据存储在session.save_path中指定的路径中的文件中.使用该会话处理程序,会话数据的年龄将根据文件的上次修改日期计算,而不是上次访问日期:

注意:如果您使用的是基于文件的默认会话处理程序,则您的文件系统必须跟踪访问时间(atime).如果您遇到FAT文件系统或任何其他无法进行atime跟踪的文件系统,那么Windows FAT不会如此,您将不得不想出另一种方法来处理垃圾收集会话.从PHP 4.2.3开始,它使用了mtime(修改日期)而不是atime.因此,对于无法进行atime跟踪的文件系统,您不会遇到问题.

因此,当会话本身仍然被认为是有效的时,可能还会发生会话数据文件被删除,因为会话数据最近没有更新.

第二个:

session.cookie_lifetime
session.cookie_lifetime指定发送到浏览器的cookie的生命周期(以秒为单位).[...]

恩,那就对了.这仅影响cookie生存期,会话本身可能仍然有效.但是服务器的任务是使会话无效,而不是客户端.所以这对任何事都没有帮助.实际上,将session.cookie_lifetime设置为0会使会话的cookie成为真正的会话cookie,该cookie仅在浏览器关闭之前有效.

结论/最佳解决方案:

最好的解决方案是实现自己的会话超时.使用表示最后一次活动(即请求)的时间的简单时间戳,并使用每个请求更新它:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minutes ago
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Run Code Online (Sandbox Code Playgroud)

每次请求更新会话数据也会更改会话文件的修改日期,以便垃圾收集器不会过早地删除会话.

您还可以使用额外的时间戳来定期重新生成会话ID,以避免对会话固定会话的攻击:

if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
    // session started more than 30 minutes ago
    session_regenerate_id(true);    // change session ID for the current session and invalidate old session ID
    $_SESSION['CREATED'] = time();  // update creation time
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • session.gc_maxlifetime 应至少等于此自定义到期处理程序的生命周期(在此示例中为1800);
  • 如果您希望在活动 30分钟后而不是在启动后30分钟后使会话setcookie过期,则还需要使用过期time()+60*30以使会话cookie保持活动状态.

  • @Metropolis:使用类似于`$ _SESSION ['LAST_ACTIVITY']的类似`$ _SESSION ['CREATED']`,其中存储用户上次活动的时间,但每次请求都会更新该值.现在,如果该时间与当前时间的差异大于1800秒,则会话的使用时间不超过30分钟. (13认同)
  • @Gumbo - 我有点困惑,你不应该将你的代码与`ini_set('session.gc-maxlifetime',1800)结合使用吗?否则,您的会话信息可能会在您的会话仍然有效时被销毁,至少如果ini设置是标准的24分钟.或者我错过了什么? (12认同)
  • @jeron:是的,你应该.但请注意,如果使用会话保存处理程序`files`,*session.gc\_maxlifetime*取决于文件的最后修改日期.因此*session.gc\_maxlifetime*应该至少等于此自定义到期处理程序的生命周期. (9认同)
  • 如果你想检查"非活动时间",你怎么能改变这个?换句话说,用户登录,只要他们继续使用该站点,它就不会将其注销.但是,如果它们在30分钟内不活动,它会将它们记录下来吗? (2认同)
  • @Metropolis:`session_unset`与`$ _SESSION = array()`的作用相同. (2认同)
  • @Gumbo:当询问有关会话的类似问题时,会大量引用/链接此问题。不幸的是,您在2月3日的评论中做出的“ 0”设置与以秒为单位的长设置有很大不同的怪癖,几乎在其他任何地方都不清楚。您介意在回答中参考它吗?还是做出CW之类的答案,以便我们可以将此问答作为所有Session FUD的重要资源? (2认同)
  • 这是一个很好的答案,有一点需要补充的是session_unset()似乎已被弃用,而有利于$ _SESSION = array(); 请参阅此处的说明:http://php.net/manual/en/function.session-destroy.php (2认同)

Raf*_*fee 129

PHP会话在30分钟内到期的简单方法.

注意:如果你想改变时间,只需用你想要的时间改变30,不要改变*60:这将给出分钟.


在几分钟内:(30*60)
在几天内:(n*24*60*60)n =没有天数


的login.php

<?php
    session_start();
?>

<html>
    <form name="form1" method="post">
        <table>
            <tr>
                <td>Username</td>
                <td><input type="text" name="text"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="pwd"></td>
            </tr>
            <tr>
                <td><input type="submit" value="SignIn" name="submit"></td>
            </tr>
        </table>
    </form>
</html>

<?php
    if (isset($_POST['submit'])) {
        $v1 = "FirstUser";
        $v2 = "MyPassword";
        $v3 = $_POST['text'];
        $v4 = $_POST['pwd'];
        if ($v1 == $v3 && $v2 == $v4) {
            $_SESSION['luser'] = $v1;
            $_SESSION['start'] = time(); // Taking now logged in time.
            // Ending a session in 30 minutes from the starting time.
            $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
            header('Location: http://localhost/somefolder/homepage.php');
        } else {
            echo "Please enter the username or password again!";
        }
    }
?>
Run Code Online (Sandbox Code Playgroud)

HomePage.php

<?php
    session_start();

    if (!isset($_SESSION['luser'])) {
        echo "Please Login again";
        echo "<a href='http://localhost/somefolder/login.php'>Click Here to Login</a>";
    }
    else {
        $now = time(); // Checking the time now when home page starts.

        if ($now > $_SESSION['expire']) {
            session_destroy();
            echo "Your session has expired! <a href='http://localhost/somefolder/login.php'>Login here</a>";
        }
        else { //Starting this else one [else1]
?>
            <!-- From here all HTML coding can be done -->
            <html>
                Welcome
                <?php
                    echo $_SESSION['luser'];
                    echo "<a href='http://localhost/somefolder/logout.php'>Log out</a>";
                ?>
            </html>
<?php
        }
    }
?>
Run Code Online (Sandbox Code Playgroud)

LogOut.php

<?php
    session_start();
    session_destroy();
    header('Location: http://localhost/somefolder/login.php');
?>
Run Code Online (Sandbox Code Playgroud)

  • 在MVC成为常态的当今时代,逻辑和演示相结合是不明智的. (41认同)
  • @stillstanding为自己说话[笑]我认为MVC是一种憎恶. (20认同)
  • @bsosca,这里的很多人都应该这样做,你应该花更多的时间担心问题的解决方案,并让OP弄清楚这一点,而不是劫持一个问题来提出你认为有效的观点;-) (9认同)
  • @bcosca 一点也不。将逻辑与标记混合本质上是 PHP 中的合法模式。而且,这从一开始就是 PHP 的全部意义所在。如果你看看现在最流行的前端框架:ReactJS,你会发现它也做了同样的事情。 (6认同)
  • 即使项目很小,只有一个程序员,MVC 也是一个好主意吗?我觉得我应该在 MVC 模型中创建我自己的项目(或者解决问题然后将其设为 MVC),但是由于缺乏 MVC 的经验,它只会成为“我如何制作这个 MVC?”的心理障碍。以及从需要解决方案的初始目标/问题中分心。 (4认同)
  • @CF 听起来像是一个蹩脚的借口。如果一块木头可以支撑一个人,你就会把它用作椅子,而不考虑有更好的解决方案,因为无论如何其他人都会这么做。对于某些人来说,有一种叫做渐进式工程的东西,这就是为什么我们在客厅里有椅子而不是长凳或普通木原木。ReactJS 并不是真正的大金字塔。在我看来,JSX 是一个弗兰肯斯坦。 (3认同)

Ros*_*oss 39

这是在一段时间后将用户注销吗?设置会话创建时间(或到期时间),然后检查每个页面上的负载可以处理它.

例如:

$_SESSION['example'] = array('foo' => 'bar', 'registered' => time());

// later

if ((time() - $_SESSION['example']['registered']) > (60 * 30)) {
    unset($_SESSION['example']);
}
Run Code Online (Sandbox Code Playgroud)

编辑:我觉得你的意思是别的.

您可以使用session.gc_maxlifetimeini设置在一定生命周期后删除会话:

编辑: ini_set('session.gc_maxlifetime',60*30);

  • 会话cookie生命周期存在一些问题,最值得注意的是,它依赖于客户端来强制执行它.cookie的生命周期是允许客户端清理无用/过期的cookie,不要与任何安全相关的东西混淆. (2认同)

Pab*_*zos 22

这篇文章展示了几种控制会话超时的方法:http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions

恕我直言第二个选择是一个很好的解决方案

<?php
/***
 * Starts a session with a specific timeout and a specific GC probability.
 * @param int $timeout The number of seconds until it should time out.
 * @param int $probability The probablity, in int percentage, that the garbage 
 *        collection routine will be triggered right now.
 * @param strint $cookie_domain The domain path for the cookie.
 */
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
    // Set the max lifetime
    ini_set("session.gc_maxlifetime", $timeout);

    // Set the session cookie to timout
    ini_set("session.cookie_lifetime", $timeout);

    // Change the save path. Sessions stored in teh same path
    // all share the same lifetime; the lowest lifetime will be
    // used for all. Therefore, for this to work, the session
    // must be stored in a directory where only sessions sharing
    // it's lifetime are. Best to just dynamically create on.
    $seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
    $path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
    if(!file_exists($path)) {
        if(!mkdir($path, 600)) {
            trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
        }
    }
    ini_set("session.save_path", $path);

    // Set the chance to trigger the garbage collection.
    ini_set("session.gc_probability", $probability);
    ini_set("session.gc_divisor", 100); // Should always be 100

    // Start the session!
    session_start();

    // Renew the time left until this session times out.
    // If you skip this, the session will time out based
    // on the time when it was created, rather than when
    // it was last used.
    if(isset($_COOKIE[session_name()])) {
        setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
    }
}
Run Code Online (Sandbox Code Playgroud)


Tou*_*afi 18

我明白上面的答案是正确的,但它们是在应用程序级别,为什么我们不只是使用.htaccess文件来设置过期时间?

<IfModule mod_php5.c>
    #Session timeout
    php_value session.cookie_lifetime 1800
    php_value session.gc_maxlifetime 1800
</IfModule>
Run Code Online (Sandbox Code Playgroud)


mid*_*dus 14

if (isSet($_SESSION['started'])){
    if((mktime() - $_SESSION['started'] - 60*30) > 0){
        //Logout, destroy session, etc.
    }
}
else {
    $_SESSION['started'] = mktime();
}
Run Code Online (Sandbox Code Playgroud)


Wal*_*ers 13

使用功能session_set_cookie_params来实现此功能.

session_start()调用之前需要调用此函数.

试试这个:

$lifetime = strtotime('+30 minutes', 0);

session_set_cookie_params($lifetime);

session_start();
Run Code Online (Sandbox Code Playgroud)

请参阅:http://php.net/manual/function.session-set-cookie-params.php


Tor*_*hel 10

使用如下功能实际上很容易.它使用数据库表名称'sessions',字段'id'和'time'.

每当用户再次访问您的站点或服务时,您应调用此函数以检查其返回值是否为TRUE.如果它为FALSE,则用户已过期并且会话将被销毁(注意:此函数使用数据库类来连接和查询数据库,当然您也可以在函数内部或类似的情况下执行此操作):

function session_timeout_ok() {
    global $db;
    $timeout = SESSION_TIMEOUT; //const, e.g. 6 * 60 for 6 minutes
    $ok = false;
    $session_id = session_id();
    $sql = "SELECT time FROM sessions WHERE session_id = '".$session_id."'";
    $rows = $db->query($sql);
    if ($rows === false) {
        //Timestamp could not be read
        $ok = FALSE;
    }
    else {
        //Timestamp was read succesfully
        if (count($rows) > 0) {
            $zeile = $rows[0];
            $time_past = $zeile['time'];
            if ( $timeout + $time_past < time() ) {
                //Time has expired
                session_destroy();
                $sql = "DELETE FROM sessions WHERE session_id = '" . $session_id . "'";
                $affected = $db -> query($sql);
                $ok = FALSE;
            }
            else {
                //Time is okay
                $ok = TRUE;
                $sql = "UPDATE sessions SET time='" . time() . "' WHERE session_id = '" . $session_id . "'";
                $erg = $db -> query($sql);
                if ($erg == false) {
                    //DB error
                }
            }
        }
        else {
            //Session is new, write it to database table sessions
            $sql = "INSERT INTO sessions(session_id,time) VALUES ('".$session_id."','".time()."')";
            $res = $db->query($sql);
            if ($res === FALSE) {
                //Database error
                $ok = false;
            }
            $ok = true;
        }
        return $ok;
    }
    return $ok;
}
Run Code Online (Sandbox Code Playgroud)


小智 8

在会话中存储时间戳


<?php    
$user = $_POST['user_name'];
$pass = $_POST['user_pass'];

require ('db_connection.php');

// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($user), mysql_real_escape_string($pass));

if( mysql_num_rows( $result ) > 0)
{
    $array = mysql_fetch_assoc($result);    

    session_start();
    $_SESSION['user_id'] = $user;
    $_SESSION['login_time'] = time();
    header("Location:loggedin.php");            
}
else
{
    header("Location:login.php");
}
?>
Run Code Online (Sandbox Code Playgroud)

现在,检查时间戳是否在允许的时间窗口内(1800秒是30分钟)

<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800)
{
    header("Location:login.php");
}
else
{
    // uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login
    //$_SESSION['login_time'] = time();
    echo ( "this session is ". $_SESSION['user_id'] );
    //show rest of the page and all other content
}
?>
Run Code Online (Sandbox Code Playgroud)


lne*_*pal 7

请在包含在每个页面中的包含文件中使用以下代码块.

$expiry = 1800 ;//session expiry required after 30 mins
    if (isset($_SESSION['LAST']) && (time() - $_SESSION['LAST'] > $expiry)) {
        session_unset();
        session_destroy();
    }
    $_SESSION['LAST'] = time();
Run Code Online (Sandbox Code Playgroud)


Man*_*uel 5

Christopher Kramer 在 2014 年在https://www.php.net/manual/en/session.configuration.php#115842上写的内容让我大开眼界

在 debian(基于)系统上,在运行时更改 session.gc_maxlifetime 没有实际效果。Debian 通过设置 session.gc_probability=0 来禁用 PHP 自己的垃圾收集器。相反,它有一个每 30 分钟运行一次的 cronjob(请参阅 /etc/cron.d/php5)来清理旧会话。这个 cronjob 基本上会检查你的 php.ini 并使用那里的 session.gc_maxlifetime 值来决定要清理哪些会话(请参阅 /usr/lib/php5/maxlifetime )。[...]