0

我为学校作业写了一些简单的登录脚本。我需要让用户登录将他们重定向到主页,并在主页顶部显示他们的用户名。我一直在按照我在网上找到的说明进行操作,但用户登录后主页上没有显示用户名。有人可以看看我的 PHP 代码并给我一些关于如何解决这个问题的提示吗?谢谢!

这是我的主要 php:

    <?php
    session_start();
    echo "You are logged in as " .$_SESSION['username'];
    echo "<p><a href=\"logout.php\">Click here to logout</a></p>";


    //Turn on error reporting
    ini_set('display_errors', 'On');
    //Connects to the database
    $mysqli = new mysqli("abc", "edf","xyz", "123");
    if($mysqli->connect_errno){
        echo "Connection error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
?>  


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>Test</title>
    <meta charset="UTF-8">  
    <style type="text/css">
        body {font-family:sans-serif;}
        h1 {color: #0000FF;text-align: center;}
        .fieldset-auto-width {display: inline-block;}
    </style>
</head>
<body>
    <div id="header" style="background-color:#FFA500;">
        <h1>Restaurant Review</h1>
    </div>
        //DO SOMETHING HERE
    <div id="content">
    <form method="post" action="addreview.php">     
    </div>
    </form>
</body>
</html> 

这是我的登录 php

    <?php
    ob_start();

    $username = $_POST['username'];
    $password = $_POST['password'];


    //Turn on error reporting
    ini_set('display_errors', 'On');
    //Connects to the database
    $mysqli = new mysqli("abc", "edf","xyz", "123");
    if($mysqli->connect_errno){
        echo "Connection error " . $mysqli->connect_errno . " " . $mysqli->connect_error;
    }

    $username = mysqli_real_escape_string($mysqli, $username);
    $query = "SELECT password, salt FROM member WHERE username = '$username';";

    $result = mysqli_query($mysqli, $query);

    // User not found. So, redirect to login_form again.
    if (mysqli_num_rows($result) == 0)
    {
        header('Location: login.html');
    }

    $userData = mysqli_fetch_array($result, MYSQL_ASSOC);
    $hash = hash('cs494', $userData['salt'] . hash('cs494', $password));

    //Incorrect password. Redirect to login form again
    if ($hash != $userData['password'])
    {
        header('Location: login.html');
    }else {
    //redirect to main page after successful login
        session_start();
        $_SESSION['username'] = $username;
        header('Location: main.php');
    }


?>
4

1 回答 1

1

echo在 HTML 文档之外,它可能位于您看不到它的页面上。如果您单击查看 > 来源,您可能会看到它打印在<!DOCTYPE>声明之前的文档顶部。

代替:

echo "You are logged in as " .$_SESSION['username'];
echo "<p><a href=\"logout.php\">Click here to logout</a></p>";
<!DOCTYPE html>
<html>...</html>

您应该像这样在文档中移动回声:

<!DOCTYPE html>
<html>
<head>...</head>
<body>
<?php
  echo "You are logged in as " .$_SESSION['username'];
  echo "<p><a href=\"logout.php\">Click here to logout</a></p>";
?>
...
</body>
</html>
于 2013-08-27T18:59:11.150 回答