在Ubuntu LNMP(Linux, Nginx, MySQL, PHP)环境中,实现安全的用户登录系统需要考虑多个方面,包括密码加密、会话管理、防止SQL注入和跨站脚本攻击等。以下是一个基本的步骤指南:
确保你已经安装了Nginx、MySQL和PHP。如果没有,可以使用以下命令安装:
sudo apt update
sudo apt install nginx mysql-server php-fpm php-mysql
创建一个新的数据库和用户,并授予适当的权限。
CREATE DATABASE mydatabase;
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
在数据库中创建一个用户表来存储用户信息。
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
创建一个PHP脚本来处理用户登录请求。确保使用预处理语句来防止SQL注入。
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$conn = new mysqli('localhost', 'myuser', 'mypassword', 'mydatabase');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT id, username, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
$user = $result->fetch_assoc();
if (password_verify($_POST['password'], $user['password'])) {
$_SESSION['loggedin'] = true;
$_SESSION['id'] = $user['id'];
$_SESSION['username'] = $user['username'];
header('Location: dashboard.php');
exit;
} else {
$error = "Invalid username or password.";
}
} else {
$error = "Invalid username or password.";
}
$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<?php if (isset($error)) echo "<p>$error</p>"; ?>
<form method="post" action="login.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
</body>
</html>
创建一个受保护的页面(例如dashboard.php),只有登录用户才能访问。
<?php
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header('Location: login.php');
exit;
}
echo "Welcome, " . htmlspecialchars($_SESSION['username']) . "!";
?>
确保Nginx配置正确,以便处理PHP请求。
server {
listen 80;
server_name yourdomain.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
启动Nginx和PHP-FPM服务。
sudo systemctl start nginx
sudo systemctl start php7.4-fpm
通过以上步骤,你可以实现一个基本的、安全的用户登录系统。根据具体需求,你可能还需要添加更多的安全措施,例如双因素认证、CSRF保护等。