留言板实现php
留言板实现(PHP)
使用PHP实现一个简单的留言板功能,包含留言发布、显示和存储功能。以下是核心实现步骤和代码示例。
数据库准备
创建一个MySQL数据库表用于存储留言信息:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
连接数据库
创建config.php文件处理数据库连接:
<?php
$host = 'localhost';
$dbname = 'message_board';
$username = 'root';
$password = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
?>
留言发布功能
创建post_message.php处理表单提交:
<?php
require 'config.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars($_POST['username']);
$content = htmlspecialchars($_POST['content']);
$stmt = $pdo->prepare("INSERT INTO messages (username, content) VALUES (?, ?)");
$stmt->execute([$username, $content]);
header('Location: index.php');
exit;
}
?>
留言显示功能
创建index.php显示所有留言:
<?php
require 'config.php';
$stmt = $pdo->query("SELECT * FROM messages ORDER BY created_at DESC");
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form action="post_message.php" method="post">
姓名: <input type="text" name="username" required><br>
留言: <textarea name="content" required></textarea><br>
<button type="submit">提交</button>
</form>
<div class="messages">
<?php foreach ($messages as $message): ?>
<div class="message">
<strong><?= $message['username'] ?></strong>
<p><?= nl2br($message['content']) ?></p>
<small><?= $message['created_at'] ?></small>
</div>
<hr>
<?php endforeach; ?>
</div>
</body>
</html>
安全增强
添加CSRF防护和输入验证:
// 在config.php中添加
session_start();
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
// 在表单中添加
<input type="hidden" name="token" value="<?= $_SESSION['token'] ?>">
// 在post_message.php中验证
if ($_POST['token'] !== $_SESSION['token']) {
die('Invalid CSRF token');
}
分页功能
实现留言分页显示:
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 5;
$offset = ($page - 1) * $perPage;
$stmt = $pdo->prepare("SELECT * FROM messages ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $perPage, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
$stmt->execute();
这个实现包含了留言板的基本功能,可以根据需要进一步扩展如用户注册登录、留言回复等功能。







