在PHP中实现用户登录功能,通常需要以下几个步骤:
以下是一个简单的示例:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="login.php" method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username" required>
<br>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required>
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
login.php:
<?php
session_start();
// Replace these values with your own database credentials
$db_host = 'localhost';
$db_user = 'your_username';
$db_pass = 'your_password';
$db_name = 'your_database';
// Connect to the database
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form data
$username = $_POST['username'];
$password = $_POST['password'];
// Prepare and bind the statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
// Execute the statement
$stmt->execute();
// Bind the result variables
$stmt->bind_result($id, $username, $password);
// Fetch the result
if ($stmt->fetch() && password_verify($password, $stmt['password'])) {
// Store the user information in the session
$_SESSION['user_id'] = $id;
$_SESSION['username'] = $username;
// Redirect to the dashboard
header("Location: dashboard.php");
} else {
// Display an error message
echo "Invalid username or password.";
}
// Close the statement and connection
$stmt->close();
$conn->close();
}
?>
dashboard.php:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: index.html");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title>
</head>
<body>
<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<p>This is your dashboard.</p>
<a href="logout.php">Logout</a>
</body>
</html>
logout.php:
<?php
session_start();
session_destroy();
header("Location: index.html");
?>
请注意,这个示例仅用于演示目的。在实际项目中,你需要考虑更多的安全措施,如使用HTTPS、防止SQL注入、密码哈希等。