当我单击登录时。。它不会自动将我重定向到home.php,我必须刷新页面才能将我重定向。我想第一个header()运行良好,因为它对页面刷新做出了响应。不起作用的是if语句中的第二个header()。我做错了什么?非常感谢你的帮助。
login.php
<?php
session_start();
if($_SESSION['user']!=""){
header("Location: home.php");
}
include_once 'db.php';
if(isset($_POST['login'])){
$uname = mysqli_real_escape_string($conn, $_POST['uname']);
$upass = mysqli_real_escape_string($conn, $_POST['upass']);
$sql = "SELECT * FROM users WHERE username='$uname'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
if($row['password']==$upass){
$_SESSION['user'] = $row['username'];
header("Location: home.php");
}
else{
echo "Unable to log in, please try again.";
}
}
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form method="post">
<input type="text" name="uname" placeholder="User Name" required /><br>
<input type="text" name="upass" placeholder="Password" required /><br>
<button type="submit" name="login">login</button>
</form>
</body>
</html>
home.php
<?php
session_start();
if(isset($_POST['logout']))
{
session_destroy();
unset($_SESSION['user']);
header("Location: index.php");
}
?>
Welcome <?php echo $_SESSION['user'];?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form method="post">
<button type="submit" name="logout">Sign Out</button>
</form>
</body>
db.php
<?php
$conn = new mysqli();
$conn->connect('localhost', 'singta', 'Lante1', 'wuzzdb');
if ($conn->connect_errno) { echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $mysqli->connect_error; }
?>
index.php
<?php
session_start();
if($_SESSION['user']!=""){
header("Location: home.php");
}else{
echo "You're not logged In";
}
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<br><br><br>
<a href="login.php">Login Here</a>
</body>
header()
函数调用会向浏览器发送一个标头,告诉它去哪里,但它不会停止PHP脚本的执行。因此,在用于重定向的header()
调用之后,在几乎所有情况下都应该直接在它后面放一个exit;
<?php
session_start();
if($_SESSION['user']!=""){
header("Location: home.php");
exit;
}
也在您的第二次header()
通话中。
附加说明
在尝试像这样测试之前,您还应该检查$_SESSION['user']
是否存在
session_start();
if( isset($_SESSION['user']) && $_SESSION['user']!=""){
header("Location: home.php");
exit;
}
这需要在会话中测试user
,就好像他们没有登录一样——它实际上并不存在。
这是在关闭错误显示的LIVE服务器上学习PHP的问题之一。因此,当你在学习甚至之后,在实时服务器上开发脚本时,记得在开发的脚本顶部添加这两行
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
但是,当脚本以其糟糕的形式运行时,请记住删除,以向用户显示这种错误。