为什么没有显示用户名?

时间:2013-08-27 18:55:08

标签: php mysql session-variables

我为学校作业写了一些简单的登录脚本。我需要让用户登录将其重定向到主页面,并在主页面上显示他们的用户名。我一直在按照我在网上找到的说明进行操作,但是在用户登录后,用户名不显示在主页面中。有人可以查看我的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');
    }


?>

1 个答案:

答案 0 :(得分:1)

您是echo - 在HTML文档之外,它可能位于您无法看到它的页面上。如果您点击查看&gt;来源您可能会在<!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>