用php实现留言板
创建数据库表
留言板需要存储用户留言信息,创建一个MySQL数据库表:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100),
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
数据库连接配置
创建config.php文件存放数据库连接信息:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'message_board');
?>
留言提交处理
创建submit.php处理表单提交:
<?php
require 'config.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars(trim($_POST['username']));
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
$content = htmlspecialchars(trim($_POST['content']));
if (!empty($username) && !empty($content)) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$stmt = $conn->prepare("INSERT INTO messages (username, email, content) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $content);
$stmt->execute();
$stmt->close();
$conn->close();
header('Location: index.php');
exit;
}
}
?>
显示留言列表
创建index.php显示所有留言:
<?php
require 'config.php';
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$result = $conn->query("SELECT * FROM messages ORDER BY created_at DESC");
$messages = $result->fetch_all(MYSQLI_ASSOC);
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form action="submit.php" method="post">
姓名: <input type="text" name="username" required><br>
邮箱: <input type="email" name="email"><br>
留言: <textarea name="content" required></textarea><br>
<button type="submit">提交</button>
</form>
<hr>
<?php foreach ($messages as $message): ?>
<div class="message">
<h3><?= htmlspecialchars($message['username']) ?></h3>
<small><?= $message['created_at'] ?></small>
<p><?= nl2br(htmlspecialchars($message['content'])) ?></p>
</div>
<hr>
<?php endforeach; ?>
</body>
</html>
安全增强措施
添加CSRF防护和输入验证:
// 在config.php中添加
session_start();
// 在表单页生成token
$_SESSION['token'] = bin2hex(random_bytes(32));
// 在表单中添加隐藏域
<input type="hidden" name="token" value="<?= $_SESSION['token'] ?>">
// 在submit.php中验证token
if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token']) {
die('无效的CSRF令牌');
}
分页功能实现
修改index.php添加分页:
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 5;
$offset = ($page - 1) * $perPage;
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$total = $conn->query("SELECT COUNT(*) FROM messages")->fetch_row()[0];
$pages = ceil($total / $perPage);
$result = $conn->query("SELECT * FROM messages ORDER BY created_at DESC LIMIT $offset, $perPage");
$messages = $result->fetch_all(MYSQLI_ASSOC);
$conn->close();
// 在页面底部添加分页导航
<div class="pagination">
<?php for ($i = 1; $i <= $pages; $i++): ?>
<a href="?page=<?= $i ?>" <?= $i === $page ? 'class="active"' : '' ?>><?= $i ?></a>
<?php endfor; ?>
</div>






