我已经创建了一个登录脚本,它运行良好,但我想实现会话。。我目前遇到了一些问题,因为我的会话脚本只执行了一部分。下面是我的登录脚本和我希望它重定向到的测试页面,如果用户登录了。我希望它显示测试页面,否则,我希望它重新定向到登录页面(或者在这种情况下,index.php文件),并要求用户登录。。。参见下面的代码:
loginconfig.php:
<?php
// Create a connection
include("dbconfig.php");
if (isset($_POST['submit'])) {
if (empty($_POST['username']) or empty($_POST['password'])) {
header("location:index.php?msg0=Please complete the required fields.");
}
elseif (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = mysqli_query($conn, "SELECT * FROM logininformation WHERE username = '$username' and password = '$password'") or die(mysqli_error($conn));
$login = ($sql) ? mysqli_fetch_assoc($sql) : false;
if (($login) == 0) {
header("location:index.php?msg1=Invalid username or password, please try again.");
}
elseif (($login) > 0) {
session_start();
$_SESSION['login'] = $_POST['username'];
//header("location:index.php?bid=$username&msg2=You are unable to log in at this time. Website is under construction.");
header("location:test.php?bid=$sessionwork");
}
}
}
?>
test.php:
<?php
session_start();
include("dbconfig.php");
$username = $_GET['bid'];
var_dump($_SESSION['login'];
// If user is logged in:
if(!empty($_SESSION['login'])){
echo "Welcome $username";
}
// If user is not logged in:
elseif(!isset($_SESSION['login'])){
header("location:index.php?msg4=You need to be logged in!");
}
?>
<html>
<head>
<title> user page </title>
</head>
<body>
<form name="logout" method="post" action="logout.php">
<input type="submit" name="logout" value="logout">
</form>
</body>
</html>
logout.php
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
<a href="index.php"> Homepage </a>
</html>
现在,如果您查看test.php文件。。我有点告诉它要检查用户是否登录。但不幸的是,该脚本只能在用户未登录时执行脚本。重定向到index.php……即使用户输入了正确的登录凭据并实际登录。这可能是什么问题?
任何帮助都将不胜感激。
在test.php中应该是这样的:
if(isset($_SESSION['login'])){
echo "Welcome $_SESSION['login']";
}
else{
header("location:index.php?msg4=You need to be logged in!");
}
同样的错误在loginconfig.php中重复出现。
最初,我没有logout.php文件。。因此,我犯了一个错误,没有破坏我的会议。我必须对最初的脚本进行的更改是创建一个logout.php文件。但当我这样做的时候,问题仍然存在。。为了让它工作。。我对logout.php文件进行了以下更改。。见下文:
之前:
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
<a href="index.php"> Homepage </a>
</html>
之后:
<?php
session_start();
session_destroy();
header("location:index.php");
exit();
?>
感谢那些提供帮助的人,特别是@Epodax的大力支持。