php 浏览器选项卡关闭时销毁会话
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10958769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
destroy session when broswer tab closed
提问by beginner web developer
I have users login/logout application: I want to destroy session, its working fine when I close the browser (( all tabs )) , IE , Firefox working. But I want to destroy the session when user close the single tab . I am using :
我有用户登录/注销应用程序:我想销毁会话,当我关闭浏览器((所有选项卡)),IE,Firefox 工作正常时,它工作正常。但是我想在用户关闭单个选项卡时销毁会话。我在用 :
session_set_cookie_params(0);
session_start();
回答by Marc B
Browsers only destroy session cookies when the entire browser process is exited. There is no reliable method to determine if/when a user has closed a tab. There is an onbeforeunloadhandler you can attach to, and hopefully manage to make an ajax call to the server to say the tab's closing, but it's not reliable.
浏览器只有在整个浏览器进程退出时才会销毁会话 cookie。没有可靠的方法来确定用户是否/何时关闭了选项卡。onbeforeunload您可以附加一个处理程序,并希望设法对服务器进行 ajax 调用以告知选项卡已关闭,但这并不可靠。
And what if the user has two or more tables open on your site? If they close one tab, the other one would effectively be logged out, even though the user fully intended to keep on using your site.
如果用户在您的站点上打开了两个或多个表怎么办?如果他们关闭一个选项卡,即使用户完全打算继续使用您的站点,另一个选项卡也会被有效地注销。
回答by Sanjay
Solution is to implement a session timeout with own method. Use a simple time stamp that denotes the time of the last request and update it with every request:
解决方案是使用自己的方法实现会话超时。使用一个简单的时间戳来表示上次请求的时间,并在每次请求时更新它:
You need to code something similar to this
您需要编写类似于此的代码
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// request 30 minates ago
session_destroy();
session_unset();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time
More about this you can found here which is similar to your question Destroy or unset session when user close the browser without clicking on logout.
您可以在此处找到更多关于此的信息,这类似于您的问题Destroy or unset session when user close the browser without click out。
It covers all you need.
它涵盖了您所需要的一切。
回答by Rachid
But you need to add code to function endsession which is JavaScript function, you can use ajax to call your logout.php. it has worked for me:
但是你需要在函数endsession这个JavaScript函数中添加代码,你可以使用ajax调用你的logout.php。它对我有用:
$.ajax({
url:"logout.php",
method:'POST',
contentType:false,
processData:false,
success:function(data)
{
alert("session destroyed");
}
});

