我正在研究 php 中的 php session 概念。使用 jquery 和 php 创建登录页面,并在我登录 session 运行时为所有页面创建 session 我可以在另一个选项卡中打开登录的 url,这很好用,但我在注销时遇到问题。
当我在打开的浏览器选项卡之一注销时,如果我刷新页面被注销,其他选项卡仍然手动运行。我的要求是当我在其中一个选项卡中注销时,其他选项卡应该自动注销而不是手动注销。
数据库文件
<?php
session_start();
$con = mysqli_connect("localhost", "root", "","testing") or die ("Oops! Server not connected"); // Connect to the host
?>
登录.php
<?php
include 'db.php';
if(isset($_SESSION['username']) && $_SESSION['username'] != '')
{ // Redirect to secured user page if user logged in
echo '<script type="text/javascript">window.location = "userpage.php"; </script>';
}
?>
<html>
<body>
<form>
<table class="mytable">
<tr>
<td>Username</td>
<td>
<input type="text" name="username" id="username" class="as_input" value="s"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name="password" id="password" class="as_input" value="s"/>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="login" id="login" class="as_button" value="Login »" />
</td>
</tr>
</table>
</form>
</body>
</html>
欢迎主页
<?php
include 'db.php';
if(!isset($_SESSION['username']) || $_SESSION['username'] == '')
{
echo '<script type="text/javascript">window.location = "login.php"; </script>';
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="as_wrapper">
<h2>
welcome to home page
</h2>
<a href="logout.php" class="a">logout</a><br><br>
<a href='#'>test link</a>
</div>
</body>
</html>
logout.php
<?php
include 'library.php';
session_destroy();
unset($_SESSION['username']);
unset($_SESSION['password']);
echo '<script type="text/javascript">window.location = "login.php"; </script>';
?>
最佳答案
创建一个 php 页面:
检查状态.php
<?php
session_start();
if(isset($_SESSION['username']) && $_SESSION['username'] != '')
echo true;
else
echo false;
?>
现在每个页面都有这个 jQuery 代码:
var _delay = 3000;
function checkLoginStatus(){
$.get("checkStatus.php", function(data){
if(!data) {
window.location = "logout.php";
}
setTimeout(function(){ checkLoginStatus(); }, _delay);
});
}
checkLoginStatus();
因此,每个页面在一定延迟后都会重复调用一个 js 函数,该函数将通过对 php 文件(您创建的)进行 ajax 调用来检查登录状态。如果用户从任何注销,它将破坏浏览器中的 session 并使所有选项卡重定向到 logout.php 页面。
关于javascript - 当用户在 php 中打开的选项卡之一注销时自动注销所有打开的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689846/