在页面离开时销毁 PHP 会话 [英] Destroy PHP session on page leaving
问题描述
当用户离开特定页面时,我需要销毁会话.我在页面末尾使用 session_destroy()
但它对我来说不可行,因为我的页面有分页.我的页面是:abc.php?page=1
或 abc.php?page=2
或 abc.php?page=3
.
I need to destroy a session when user leave from a particular page. I use session_destroy()
on the end of the page but its not feasible for me because my page has pagination. My page is: abc.php?page=1
or abc.php?page=2
or abc.php?page=3
.
因此,当用户从 abc.php
页面离开时,我需要销毁会话.如何在不使用 cookie 的情况下做到这一点?
So, I need to destroy a session when a user leaves from abc.php
page. How can I do it without using a cookie?
推荐答案
在用户离开页面时做某事是错误的方法,因为你不知道用户是否会导航到一个完全不同的页面(比如联系.php 为了论证),否则他/她将直接转到 abc.php 的下一页,正如 Borealid 指出的那样,没有 JS 就无法做到这一点.相反,您可以简单地添加一个检查并查看用户是否来自 abc.php:
Doing something when the user navigates away from a page is the wrong approach because you don't know if the user will navigate to a whole different page (say contact.php for the sake of the argument) or he/she will just go to the next page of abc.php and, as Borealid pointed out, you can't do it without JS. Instead, you could simply add a check and see if the user comes from abc.php:
首先,在您的 abc.php 文件中,在 $_SESSION 数组中设置一个唯一变量,该变量将作为用户已在此页面上的标记:
First, in your abc.php file set a unique variable in the $_SESSION array which will act as a mark that the user has been on this page:
$_SESSION['previous'] = basename($_SERVER['PHP_SELF']);
然后,在所有页面上添加这个,在任何输出之前检查用户是否来自 abc.php:
Then, add this on all pages, before any output to check if the user is coming from abc.php:
if (isset($_SESSION['previous'])) {
if (basename($_SERVER['PHP_SELF']) != $_SESSION['previous']) {
session_destroy();
### or alternatively, you can use this for specific variables:
### unset($_SESSION['varname']);
}
}
这样,只有当用户来自 abc.php 并且当前页面是另一个页面时,您才会销毁会话(或特定变量).
This way you will destroy the session (or specific variables) only if the user is coming from abc.php and the current page is a different one.
我希望我能够清楚地解释这一点.
I hope I was able to clearly explain this.
这篇关于在页面离开时销毁 PHP 会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!