我需要保持一个会话存活30分钟,然后销毁它。


当前回答

您可以直接使用DB作为替代。我使用一个DB函数来做这件事,我称之为chk_lgn。

检查登录检查,看看他们是否登录,在这样做的时候,它将检查的日期时间戳设置为用户db行/列中的最后一个活动。

我也会核对时间。这对我来说是有效的,因为我对每个页面都使用这个函数。

附注:我所见过的人中,没有人建议使用纯DB解决方案。

其他回答

您可以直接使用DB作为替代。我使用一个DB函数来做这件事,我称之为chk_lgn。

检查登录检查,看看他们是否登录,在这样做的时候,它将检查的日期时间戳设置为用户db行/列中的最后一个活动。

我也会核对时间。这对我来说是有效的,因为我对每个页面都使用这个函数。

附注:我所见过的人中,没有人建议使用纯DB解决方案。

PHP是如何处理会话的,初学者很难理解。这可能会帮助他们概述会话的工作原理: 会话如何工作(自定义会话处理程序)

在这里你可以设定时间

$lifespan = 1800;
ini_set('session.gc_maxlifetime', $lifespan); //default life time
if (isSet($_SESSION['started'])){
    if((mktime() - $_SESSION['started'] - 60*30) > 0){
        //Logout, destroy session, etc.
    }
}
else {
    $_SESSION['started'] = mktime();
}

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

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


分钟:(30 * 60) (n * 24 * 60 * 60) n = no天


login。

<?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!";
        }
    }
?>

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

LogOut.php

<?php
    session_start();
    session_destroy();
    header('Location: http://localhost/somefolder/login.php');
?>