要在PHP中创建一个简单的登录系统,您可以遵循以下步骤:
action属性设置为PHP脚本的文件名(例如login.php),并将method属性设置为post。<!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>
<h2>Login</h2>
<form action="login.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
login.php的PHP文件,用于处理登录表单提交的数据。首先,检查表单是否已提交,然后使用trim()函数清除用户输入中的任何空格。接着,使用password_hash()函数对密码进行哈希处理,并将哈希值与数据库中的用户密码进行比较。如果找到匹配项,则创建一个会话并将用户重定向到受保护的页面;否则,显示一条错误消息。<?php
session_start();
// Replace 'your_database_connection_string' with your actual database connection string
$db_connection = 'your_database_connection_string';
// Connect to the database
$conn = new mysqli($db_connection);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the username and password from the form
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
// Prepare and bind the statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
// Check if a user with the given username exists
if ($result->num_rows > 0) {
// Bind the result variables
$user = $result->fetch_assoc();
$hashed_password = $user["password"];
// Verify the password
if (password_verify($password, $hashed_password)) {
// Password is correct, start the session
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
// Redirect to the protected page
header("Location: protected_page.php");
exit();
} else {
// Incorrect password
echo "Invalid username or password.";
}
} else {
// No user with the given username exists
echo "Invalid username or password.";
}
}
$stmt->close();
$conn->close();
?>
protected_page.php的PHP文件,用于显示受保护的页面。在此文件中,首先检查用户是否已登录,然后根据登录状态显示不同的内容。<?php
session_start();
if (!isset($_SESSION["loggedin"]) || !$_SESSION["loggedin"]) {
// User is not logged in, redirect to the login page
header("Location: login.html");
exit();
}
// User is logged in, display the protected content
echo "<h2>Welcome, " . $_SESSION["username"] . "!</h2>";
echo "<p>This is a protected page.</p>";
?>
请注意,这只是一个简单的示例,实际应用中可能需要考虑更多的安全措施,例如使用HTTPS、防止SQL注入、限制登录尝试次数等。