apache 如何在PHP中关闭标签时销毁会话?

siotufzp  于 2023-03-31  发布在  Apache
关注(0)|答案(1)|浏览(67)

每当选项卡关闭时,我都想销毁会话。
我已经设置了会话的到期时间,但它不符合我的要求。如果我重新启动Apache,然后会话被销毁,但我希望代码销毁关闭选项卡上的会话。

9rnv2umw

9rnv2umw1#

当用户关闭一个标签页时,JavaScript可以用来检测它并向服务器发送一个 AJAX 请求,结束PHP会话。这是你如何完成的:

<script>
  window.addEventListener('beforeunload', function (event) {
    navigator.sendBeacon('sessionDestroy.php');
  });
</script>

并创建sessionDestroy.php文件来销毁会话(完全销毁会话的最佳方法-即使浏览器未关闭)

<?php
    session_start();
    $_SESSION = array();

    // If it's desired to kill the session, also delete the session cookie.
    // Note: This will destroy the session, and not just the session data!
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    // Finally, destroy the session.
    session_destroy();
?>

相关问题