PHP - header('location:profile.php'); not working


PHP - header('location:profile.php'); not working

当我点击登录时,它一直说无效的登录信息。我想把它放到profile。php我用的是header('location:profile.php'),我想知道有什么问题?请大家看一下,如果我遗漏了什么或有打字错误,请告诉我。谢谢!

    <?php
//database information
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
//connect to database
mysql_connect($host, $user, $pass);
mysql_select_db($db);
//select table
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
    $res = mysql_query($sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Admin Login</title>
<link href="../sources/stylesheet.css" rel="stylesheet" type="text/css" />
</head><body>
<div id="content_login">
  <div id="header">
    <p align="center"><u>NJROTC ADMINS</u></p>
    <div id="Quote">
      <p align="center">You cannot be on this page if you weren't given the login information!  </p>
    </div>
  </div>
  <p>&nbsp;</p>
  <p><br />
  </p>
  <form id="form1" name="form1" method="post" action="/njrotc/pages/login.php">
    <table width="331" height="141" border="0">
      <tr>
        <td width="112">Username</td>
        <td width="178"><input type="text" name="username" id="text2" /></td>
      </tr>
      <tr>
        <td>Password</td>
        <td><input type="password" name="password" id="password" /></td>
      </tr>
      <tr>
        <td colspan="2"><div class="php">
          <?php
if (isset($_POST['username'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    if (mysql_num_rows($res) == 1) {
    echo "You have successfully logged in.";
    exit();
    } else {
    echo "Invalid log in information.";
    exit();
        header ('location:profile.php');
    }
}
?>
        </div></td>
      </tr>
      <tr>
        <td><input type="submit" name="submit" id="submit" value="Log In" /></td>
        <td>&nbsp;</td>
      </tr>
    </table>
  </form>
</div>
</body>
</html>

这是你的代码:

echo "Invalid log in information.";
exit();
    header ('location:profile.php');

首先,当你执行一个echo服务器发送头到浏览器,所以你不能在header调用之前。但是在这之后,在header ('location:profile.php');调用之前,你有一个exit();。所以它永远不会执行它。只需这样做:

// echo "Invalid log in information.";
// exit();
header ('location:profile.php');

注释掉echoexit,以防有正当理由让你把它们放在那里。也许是为了调试?但是如果这是在生产中,则不需要这些。