自建留言板

Reno 于 2025-08-10 发布

功能说明

✔ 分页显示留言(每页 5 条)

✔ 验证码防止机器人提交

✔ 限制 60 秒才能同一个 IP 再次留言(简单防刷)

✔ 防 XSS 攻击(htmlspecialchars()

✔ 点击验证码图片可以刷新

MySQL

连接数据库

mysql -h 主机地址 -P 端口 -u 用户名 -p

创建数据库

CREATE DATABASE message_board CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE message_board;
CREATE TABLE messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    content TEXT NOT NULL,
    ip VARCHAR(45) NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

index.php

<?php
session_start();

// ======== 数据库配置 ========
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "message_board";

$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die("数据库连接失败: " . $conn->connect_error);
}

// ======== 分页参数 ========
$per_page = 5; // 每页留言数
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;

// ======== 验证码生成 ========
if (isset($_GET['captcha'])) {
    header("Content-type: image/png");
    $image = imagecreate(80, 30);
    $bg = imagecolorallocate($image, 255, 255, 255);
    $text_color = imagecolorallocate($image, 0, 0, 0);
    $code = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 4);
    $_SESSION['captcha'] = $code;
    imagestring($image, 5, 15, 8, $code, $text_color);
    imagepng($image);
    imagedestroy($image);
    exit;
}

// ======== 处理留言提交 ========
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name']);
    $content = trim($_POST['content']);
    $captcha = trim($_POST['captcha']);
    $ip = $_SERVER['REMOTE_ADDR'];

    // 验证码检查
    if (strcasecmp($captcha, $_SESSION['captcha']) != 0) {
        $error = "验证码错误!";
    } elseif ($name === "" || $content === "") {
        $error = "昵称和留言不能为空!";
    } else {
        // 防刷:检查同一 IP 60 秒内是否发过
        $stmt = $conn->prepare("SELECT created_at FROM messages WHERE ip=? ORDER BY created_at DESC LIMIT 1");
        $stmt->bind_param("s", $ip);
        $stmt->execute();
        $stmt->bind_result($last_time);
        if ($stmt->fetch() && (time() - strtotime($last_time) < 60)) {
            $error = "请不要频繁留言,请稍后再试。";
        } else {
            $stmt->close();
            // 插入留言
            $stmt = $conn->prepare("INSERT INTO messages (name, content, ip) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $name, $content, $ip);
            $stmt->execute();
            $stmt->close();
            header("Location: index.php");
            exit;
        }
        $stmt->close();
    }
}

// ======== 获取留言总数 ========
$total_result = $conn->query("SELECT COUNT(*) AS total FROM messages");
$total_row = $total_result->fetch_assoc();
$total = $total_row['total'];
$total_pages = ceil($total / $per_page);

// ======== 获取当前页留言 ========
$offset = ($page - 1) * $per_page;
$stmt = $conn->prepare("SELECT * FROM messages ORDER BY created_at DESC LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $per_page);
$stmt->execute();
$result = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>留言板</title>
<style>
body {
    font-family: "Segoe UI", Arial, sans-serif;
    background: #f4f6f9;
    color: #333;
    width: 700px;
    margin: 30px auto;
    line-height: 1.6;
}

h1 {
    text-align: center;
    margin-bottom: 25px;
    color: #444;
}

/* 表单 */
form {
    background: #fff;
    padding: 20px 25px;
    margin-bottom: 25px;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

input, textarea {
    width: 100%;
    padding: 10px 12px;
    margin: 8px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    box-sizing: border-box;
    transition: all 0.2s ease;
}

input:focus, textarea:focus {
    border-color: #4a90e2;
    outline: none;
    box-shadow: 0 0 5px rgba(74,144,226,0.3);
}

button {
    background: #4a90e2;
    color: #fff;
    border: none;
    padding: 10px 18px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    transition: background 0.2s ease;
}

button:hover {
    background: #357abd;
}

/* 错误提示 */
.error {
    background: #ffeaea;
    padding: 10px 15px;
    border: 1px solid #e07b7b;
    color: #c0392b;
    border-radius: 5px;
    margin-bottom: 15px;
}

/* 留言样式 */
.message {
    background: #fff;
    margin-bottom: 15px;
    padding: 15px 20px;
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.08);
    transition: transform 0.2s ease;
}
.message:hover {
    transform: translateY(-2px);
}
.message strong {
    color: #4a90e2;
}
.message small {
    display: block;
    margin-top: 5px;
    font-size: 12px;
    color: #888;
}

/* 图片验证码 */
img[alt="验证码"] {
    border: 1px solid #ccc;
    border-radius: 5px;
    background: #fdfdfd;
    margin-left: 10px;
    box-shadow: 0 0 3px rgba(0,0,0,0.1);
}

/* 分页 */
.pagination {
    text-align: center;
    margin: 20px 0;
}
.pagination a, 
.pagination span {
    display: inline-block;
    margin: 0 4px;
    padding: 6px 10px;
    border-radius: 4px;
    text-decoration: none;
    font-size: 14px;
    border: 1px solid #ddd;
    transition: background 0.2s ease, color 0.2s ease;
}
.pagination a {
    color: #4a90e2;
    background: #fff;
}
.pagination a:hover {
    background: #4a90e2;
    color: #fff;
}
.pagination span {
    background: #4a90e2;
    color: #fff;
    border: 1px solid #4a90e2;
}
</style>
</head>
<body>
<h1>留言板</h1>

<?php if (!empty($error)): ?>
<div class="error"><?php echo $error; ?></div>
<?php endif; ?>

<form method="POST">
    <input type="text" name="name" placeholder="昵称" required>
    <textarea name="content" placeholder="留言内容" required></textarea>
    <input type="text" name="captcha" placeholder="输入验证码" required style="width:120px; display:inline-block;">
    <img src="index.php?captcha=1" onclick="this.src='index.php?captcha=1&'+Math.random()" alt="验证码" style="cursor: pointer; vertical-align: middle;">
    <br><br>
    <button type="submit">提交</button>
</form>

<?php while($row = $result->fetch_assoc()): ?>
<div class="message">
    <strong><?php echo htmlspecialchars($row['name']); ?></strong> 说:
    <p><?php echo nl2br(htmlspecialchars($row['content'])); ?></p>
    <small><?php echo $row['created_at']; ?> | IP: <?php echo $row['ip']; ?></small>
</div>
<?php endwhile; ?>

<!-- 分页导航 -->
<div class="pagination">
    <?php if ($page > 1): ?>
        <a href="?page=<?php echo $page - 1; ?>">« 上一页</a>
    <?php endif; ?>

    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
        <?php if ($i == $page): ?>
            <span><?php echo $i; ?></span>
        <?php else: ?>
            <a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
        <?php endif; ?>
    <?php endfor; ?>

    <?php if ($page < $total_pages): ?>
        <a href="?page=<?php echo $page + 1; ?>">下一页 »</a>
    <?php endif; ?>
</div>

</body>
</html>
<?php
$stmt->close();
$conn->close();
?>