离开页面时销毁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屋!