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