login.php1.8 KB
<?php
require 'config.php';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
$stmt = $pdo->prepare("SELECT id, username, password, role FROM users WHERE username = :u");
$stmt->execute([':u' => $username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
if ($user['role'] === 'admin') {
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];
header('Location: index.php'); exit;
} else {
$error = '该账号没有后台管理权限!';
}
} else {
$error = '用户名或密码错误!';
}
}
?>
<!DOCTYPE html>
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>后台登录</title>
</head>
<body style="display:flex;justify-content:center;align-items:center;height:100vh;background:#f0f2f5;">
<div style="background:#fff;padding:40px;border-radius:8px;width:300px;">
<h2 style="text-align:center;margin-bottom:20px;">博客后台登录</h2>
<?php if($error) echo "<p style='color:red;text-align:center;'>$error</p>"; ?>
<form method="POST">
<input type="text" name="username" placeholder="管理员账号" required style="width:100%;padding:10px;margin-bottom:10px;box-sizing:border-box;"><br>
<input type="password" name="password" placeholder="密码" required style="width:100%;padding:10px;margin-bottom:15px;box-sizing:border-box;"><br>
<button type="submit" style="width:100%;padding:10px;background:#333;color:#fff;border:none;cursor:pointer;">登 录</button>
</form>
</div>
</body></html>