php实现login
PHP 登录功能实现
数据库连接与配置
创建 config.php 文件存储数据库连接信息:
<?php
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
登录表单设计
创建 login.php 文件包含 HTML 表单:
<form action="authenticate.php" method="post">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
验证逻辑实现
创建 authenticate.php 处理登录请求:
<?php
session_start();
require 'config.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT id, password FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if ($stmt->rowCount() == 1) {
$user = $stmt->fetch();
if (password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
header("Location: dashboard.php");
exit();
}
}
$error = "Invalid credentials";
}
?>
密码安全处理
注册时应使用 password_hash() 存储密码:

$hashed_password = password_hash($plain_password, PASSWORD_DEFAULT);
会话管理
创建 dashboard.php 显示受保护内容:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
echo "Welcome to your dashboard!";
?>
安全增强措施
添加 CSRF 防护令牌:

// 在登录表单中
$_SESSION['token'] = bin2hex(random_bytes(32));
echo '<input type="hidden" name="token" value="'.$_SESSION['token'].'">';
// 在验证逻辑中
if (!hash_equals($_SESSION['token'], $_POST['token'])) {
die('Invalid CSRF token');
}
错误处理优化
显示友好的错误消息:
if (isset($error)) {
echo '<div class="error">'.$error.'</div>';
}
完整登录流程
- 用户访问
login.php并填写表单 - 表单提交到
authenticate.php进行验证 - 验证成功后创建会话并重定向
- 未验证用户访问受限页面时重定向到登录页
密码重置功能
可选实现密码重置流程:
// 生成重置令牌
$token = bin2hex(random_bytes(50));
$stmt = $conn->prepare("UPDATE users SET reset_token=?, token_expires=DATE_ADD(NOW(), INTERVAL 1 HOUR) WHERE email=?");
$stmt->execute([$token, $email]);
// 发送包含重置链接的邮件
$reset_link = "https://example.com/reset.php?token=$token";






