【发布时间】:2019-05-12 09:59:31
【问题描述】:
是否可以在访问者关闭或离开页面时创建自动注销?我知道我使用的代码不是很好,但我需要一些没有数据库的东西。无论如何,我使用 2 个文件,一个 login.php 和 index.php。我才刚开始写 PHP,所以一个“简单”的解释会非常受欢迎;)
我现在使用的登录代码:
登录.php
<?php defined('DS') OR die('No direct access allowed.');
$users = array(
"admin" => "admin"
);
if(isset($_GET['logout'])) {
$_SESSION['username'] = '';
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(isset($_POST['username'])) {
if($users[$_POST['username']] !== NULL && $users[$_POST['username']] == $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
header('Location: ' . $_SERVER['PHP_SELF']);
}else {
//invalid login
echo "<p>Username and/or password is incorrect!</p>";
}
}
echo '<form method="post" action="'.SELF.'">
<h2>Login</h2>
<p><label for="username">Username</label> <input type="text" id="username" name="username" value="" /></p>
<p><label for="password">Password</label> <input type="password" id="password" name="password" value="" /></p>
<p><input type="submit" name="submit" value="Login" class="button"/></p>
</form>';
exit;
?>
index.php
<?php
session_start();
define('DS', TRUE);
define('USERNAME', $_SESSION['username']);
define('SELF', $_SERVER['PHP_SELF'] );
if (!USERNAME or isset($_GET['logout']))
include('login.php');
?>
【问题讨论】:
-
@MasivuyeCokile 如果我理解正确,该解决方案会在特定时间后销毁会话,我实际上希望在您离开页面时销毁会话,无论如何谢谢
-
我在你给我们看的 forst 脚本中没有看到
session_start()!!! -
正确,它在第二个文件中。那是问题吗? @RiggsFolly
-
是的,必须在所有想要使用会话的脚本中,并且在脚本的顶部