• 技术文章 >后端开发 >php教程

    详解PHP会话如何实现在30分钟后被销毁(附代码实例)

    藏色散人藏色散人2022-11-14 16:45:44转载214
    本文给大家介绍有关PHP会话如何指定时间销毁的问题,下面就给大家详细介绍如何通过session_destroy()这个函数来销毁会话的,希望对需要的朋友有所帮助~

    php入门到就业线上直播课:进入学习

    PHP有一个核心函数session_destroy()来清除所有会话值。它是一个简单的没有参数的函数,返回一个布尔值true或false。

    PHP的会话ID默认存储在一个cookie中。一般来说,该会话cookie文件的名字是PHPSESSID。session_destroy函数不会取消cookie中的sessionid。

    为了 "完全 "销毁会话,会话ID也必须被取消设置。

    这个快速的例子使用session_destroy()来销毁会话。它使用set_cookie()方法,通过过期的PHP会话ID来杀死整个会话。

    快速例子

    destroy-session.php

    <?php
    // Always remember to initialize the session,
    // even before attempting to destroy it.
    
    // Destroy all the session variables.
    $_SESSION = array();
    
    // delete the session cookie also to destroy the session
    if (ini_get("session.use_cookies")) {
        $cookieParam = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $cookieParam["path"], $cookieParam["domain"], $cookieParam["secure"], $cookieParam["httponly"]);
    }
    
    // as a last step, destroy the session.
    session_destroy();

    注: 使用session_start()在PHP会话销毁后重新启动会话。 使用PHP$_SESSION取消设置特定的会话变量。对于较旧的PHP版本,请使用session_unset()。 php会话销毁输出【推荐学习:PHP视频教程

    关于此登录session_destory()示例

    让我们创建一个登录示例代码,以使用PHP会话、session_destroy等。它允许用户从当前会话登录和注销。如果您在PHP脚本中寻找完整的用户注册和登录,请使用此代码。 此示例提供了自动登录会话到期功能。

    带有登录表单的登录页

    此表单发布用户输入的用户名和密码。它验证PHP中的登录凭据。 成功登录后,它将登录状态存储到PHP会话中。它将过期时间设置为从上次登录时间起30分钟。 它将上次登录时间和到期时间存储到PHP会话中。这两个会话变量用于使会话自动过期。

    login.php

    <?php
    session_start();
    $expirtyMinutes = 1;
    ?>
    <html>
    <head>
    <title>PHP Session Destroy after 30 Minutes</title>
    <link rel='stylesheet' href='style.css' type='text/css' />
    <link rel='stylesheet' href='form.css' type='text/css' />
    </head>
    <body>
        <div class="phppot-container">
            <h1>Login</h1>
            <form name="login-form" method="post">
                <table>
                    <tr>
                        <td>Username</td>
                        <td><input type="text" name="username"></td>
                    </tr>
                    <tr>
                        <td>Password</td>
                        <td><input type="password" name="password"></td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="Sign in"
                            name="submit"></td>
                    </tr>
                </table>
            </form>
    <?php
    if (isset($_POST['submit'])) {
        $usernameRef = "admin";
        $passwordRef = "test";
        $username = $_POST['username'];
        $password = $_POST['password'];
    
        // here in this example code focus is session destroy / expiry only
        // refer for registration and login code https://phppot.com/php/user-registration-in-php-with-login-form-with-mysql-and-code-download/
        if ($usernameRef == $username && $passwordRef == $password) {
            $_SESSION['login-user'] = $username;
            // login time is stored as reference
            $_SESSION['ref-time'] = time();
            // Storing the logged in time.
            // Expiring session in 30 minutes from the login time.
            // See this is 30 minutes from login time. It is not 'last active time'.
            // If you want to expire after last active time, then this time needs
            // to be updated after every use of the system.
            // you can adjust $expirtyMinutes as per your need
            // for testing this code, change it to 1, so that the session
            // will expire in one minute
            // set the expiry time and
            $_SESSION['expiry-time'] = time() + ($expirtyMinutes * 60);
            // redirect to home
            // do not include home page, it should be a redirect
            header('Location: home.php');
        } else {
            echo "Wrong username or password. Try again!";
        }
    }
    ?>
    </div>
    </body>
    </html>

    仪表板验证PHP登录会话并显示登录和注销链接

    这是登录后重定向的目标页面。如果登录会话存在,它将显示注销链接。 一旦超时,它将调用销毁会话。php代码来销毁所有会话。 如果达到30分钟到期时间或会话为空,它会要求用户登录。

    home.php

    <?php
    session_start();
    ?>
    <html>
    <head>
    <title>PHP Session Destroy after 30 Minutes</title>
    <link rel='stylesheet' href='style.css' type='text/css' />
    <link rel='stylesheet' href='form.css' type='text/css' />
    </head>
    <body>
        <div class="phppot-container">
    <?php
    if (! isset($_SESSION['login-user'])) {
        echo "Login again!<br><br>";
        echo "<a href='login.php'>Login</a>";
    } else {
        $currentTime = time();
        if ($currentTime > $_SESSION['expiry-time']) {
            require_once __DIR__ . '/destroy-session.php';
            echo "Session expired!<br><br><a href='login.php'>Login</a>";
        } else {
            ?>
            <h1>Welcome <?php echo $_SESSION['login-user'];?>!</h1>
            <a href='logout.php'>Log out</a>
    <?php
        }
    }
    ?>
    </div>
    </body>
    </html>

    此PHP代码用于希望在会话到期前注销的用户。

    它通过要求销毁会话来销毁会话。php代码。然后,它将用户重定向到登录页面。 logout.php

    <?php
    session_start();
    require_once __DIR__ . '/destroy-session.php';
    header('Location: login.php');
    ?>

    我希望这个示例有助于理解如何销毁PHP会话。而且,这是一个完美的场景,适合解释销毁会话的必要性。

    本文系转载,原文地址:https://juejin.cn/post/7164391542164520990

    以上就是详解PHP会话如何实现在30分钟后被销毁(附代码实例)的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:juejin,如有侵犯,请联系admin@php.cn删除

    前端(VUE)零基础到就业课程:点击学习

    清晰的学习路线+老师随时辅导答疑

    快捷开发Web应用及小程序:点击使用

    支持亿级表,高并发,自动生成可视化后台。

    专题推荐:会话 PHP
    上一篇:PHP文件上传处理逻辑大梳理(全面分析) 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ❤️‍🔥共22门课程,总价3725元,会员免费学• ❤️‍🔥接口自动化测试不想写代码?• PHP会话控制:cookie和session区别与用法深入理解• php session 会话(专题)• PHP中对于会话控制里的session如何使用?• 用PHP来设置成功登录的会话(附代码实例)
    1/1

    PHP中文网