mirror of
https://github.com/zhang-pu/guestbook.git
synced 2026-12-01 09:18:27 +08:00
init: guestbook v1.0.0 首次发布
- 加固版留言系统 / 磁盘清理助手 - MIT License
This commit is contained in:
commit
06d21f90db
15 changed files with 1440 additions and 0 deletions
14
.gitignore
vendored
Normal file
14
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
# 数据目录(含 SQLite 数据库与初始密码文件)绝不入库
|
||||||
|
guestbook-data/
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
initial-admin-password.txt
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# 常见备份残留
|
||||||
|
*.bak
|
||||||
|
*.old
|
||||||
|
*.orig
|
||||||
|
*.swp
|
||||||
6
.htaccess
Normal file
6
.htaccess
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
# 仅对 Apache 有效;nginx 请参考 部署说明.md 里的 nginx 配置
|
||||||
|
Options -Indexes
|
||||||
|
<FilesMatch "\.(sql|md|log|ini|db)$">
|
||||||
|
Require all denied
|
||||||
|
</FilesMatch>
|
||||||
|
# 目录列表关闭 + 敏感文件保护(nginx 不读 .htaccess,必须另配 nginx 规则)
|
||||||
21
LICENSE
Normal file
21
LICENSE
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Zhang Pu
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
76
README.md
Normal file
76
README.md
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
# Guestbook · 轻量留言系统(PHP + SQLite)
|
||||||
|
|
||||||
|
一个零依赖、单目录部署的 PHP 留言本。前台留言 + 后台管理(回复 / 隐藏 / 删除 / 改密),数据存 SQLite,安全默认值写死在代码里(不硬编码任何密码)。
|
||||||
|
|
||||||
|
在线演示:<https://zhangpu.dev/guestbook/>
|
||||||
|
|
||||||
|
## 特性
|
||||||
|
|
||||||
|
- **零依赖**:PHP 7.4+ 即可跑,只需要 `sqlite3` / `pdo_sqlite` 扩展,不需要 MySQL、不需要 Composer
|
||||||
|
- **首次运行自动建表**,并生成 16 位随机管理员密码写到 **webroot 之外** 的数据目录(600 权限)
|
||||||
|
- **数据默认在 webroot 外**(`<site>/guestbook-data/guestbook.db`)→ 杜绝 `.db` 被直接下载
|
||||||
|
- **所有写操作走 POST + CSRF token**,删除/隐藏不再能用 GET 触发
|
||||||
|
- **会话加固**:Secure / HttpOnly / SameSite、strict mode、登录后 `session_regenerate_id()`、2 小时空闲超时
|
||||||
|
- **限流**:留言 5 条/10 分钟/IP、登录 10 次/10 分钟/IP
|
||||||
|
- **审计日志**:后台每次操作都写 `admin_logs` 表(操作人 / 动作 / IP / 时间)
|
||||||
|
- **异常不外泄**:内部错误只写日志,前台给友好提示(不泄露数据库路径)
|
||||||
|
- **安全响应头**:`X-Frame-Options` / `X-Content-Type-Options` / `CSP` / `Referrer-Policy`
|
||||||
|
- 前台**不显示留言人邮箱**(邮箱只在后台可见),`mbstring` 缺失时自动降级不致命
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1) 上传本目录所有文件到站点目录,例如 index/guestbook/
|
||||||
|
# 2) 建站外数据目录(与站点目录同级,不在 webroot 内)
|
||||||
|
cd /opt/1panel/www/sites/<域名>/
|
||||||
|
mkdir -p guestbook-data
|
||||||
|
chown www-data:www-data guestbook-data # 换成你的 php-fpm 运行用户
|
||||||
|
chmod 750 guestbook-data
|
||||||
|
|
||||||
|
# 3) 首次访问会自动建表并生成初始管理员密码
|
||||||
|
# (也可以命令行预热:cd index/guestbook && php admin-password.php --random)
|
||||||
|
|
||||||
|
# 4) 取初始密码
|
||||||
|
cat /opt/1panel/www/sites/<域名>/guestbook-data/initial-admin-password.txt
|
||||||
|
|
||||||
|
# 5) 登录后台改密码,然后删掉密码文件
|
||||||
|
cd /opt/1panel/www/sites/<域名>/index/guestbook
|
||||||
|
php admin-password.php '你的新密码'
|
||||||
|
rm -f ../guestbook-data/initial-admin-password.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
> ⚠️ **nginx 不读 `.htaccess`** —— 必须显式配置封堵规则,否则 `.db` / 备份文件会被直接下载。
|
||||||
|
> 现成片段见 [`nginx.conf.example`](nginx.conf.example),完整说明见 [`docs/部署说明.md`](docs/部署说明.md)。
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
guestbook/
|
||||||
|
├── index.php # 前台:留言列表 + 提交
|
||||||
|
├── login.php # 后台登录
|
||||||
|
├── logout.php
|
||||||
|
├── admin.php # 后台:回复 / 隐藏 / 删除 / 审计
|
||||||
|
├── admin-password.php # 命令行改密工具(仅 CLI)
|
||||||
|
├── config.php # 配置 + 工具函数 + 自动建表
|
||||||
|
├── db.sql # 建表 SQL(参考用,通常不需手工执行)
|
||||||
|
├── nginx.conf.example # nginx 封堵规则片段
|
||||||
|
└── assets/ # style.css / script.js
|
||||||
|
```
|
||||||
|
|
||||||
|
数据目录(**在 webroot 外**):`<site>/guestbook-data/`
|
||||||
|
├── `guestbook.db` # SQLite 数据库
|
||||||
|
├── `initial-admin-password.txt` # 初始密码(看完即删)
|
||||||
|
└── `guestbook.log` # 错误日志
|
||||||
|
|
||||||
|
## 环境变量(可选)
|
||||||
|
|
||||||
|
| 变量 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `GUESTBOOK_DATA_DIR` | 数据目录路径,默认 `../guestbook-data` |
|
||||||
|
| `GUESTBOOK_DB` | SQLite 文件路径,默认 `<数据目录>/guestbook.db` |
|
||||||
|
| `GUESTBOOK_ADMIN_USER` | 初始管理员用户名,默认 `admin` |
|
||||||
|
| `GUESTBOOK_ADMIN_PASS` | 初始管理员密码(不设则随机生成) |
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
52
admin-password.php
Normal file
52
admin-password.php
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* 修改管理员密码(仅命令行可用)
|
||||||
|
* 用法:php admin-password.php <新密码> [用户名]
|
||||||
|
* php admin-password.php --random [用户名] # 生成随机密码并打印
|
||||||
|
*/
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
if (PHP_SAPI !== 'cli') {
|
||||||
|
http_response_code(403);
|
||||||
|
exit("仅限命令行使用\n");
|
||||||
|
}
|
||||||
|
require_once __DIR__ . '/config.php';
|
||||||
|
|
||||||
|
$args = array_slice($argv, 1);
|
||||||
|
$random = in_array('--random', $args, true);
|
||||||
|
if ($random) { $args = array_values(array_diff($args, ['--random'])); }
|
||||||
|
|
||||||
|
$username = $args[1] ?? 'admin';
|
||||||
|
$pass = $args[0] ?? '';
|
||||||
|
if ($random || $pass === '') {
|
||||||
|
$pass = bin2hex(random_bytes(8));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mb_len($pass) < 8) {
|
||||||
|
fwrite(STDERR, "密码太短(至少 8 位)\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$db = get_db();
|
||||||
|
$st = $db->prepare('SELECT id FROM admins WHERE username = ?');
|
||||||
|
$st->bindValue(1, $username, SQLITE3_TEXT);
|
||||||
|
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);
|
||||||
|
if (!$row) {
|
||||||
|
fwrite(STDERR, "账号不存在: {$username}\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
$u = $db->prepare('UPDATE admins SET password_hash = ? WHERE id = ?');
|
||||||
|
$u->bindValue(1, password_hash($pass, PASSWORD_DEFAULT), SQLITE3_TEXT);
|
||||||
|
$u->bindValue(2, (int)$row['id'], SQLITE3_INTEGER);
|
||||||
|
$u->execute();
|
||||||
|
echo "已更新账号 {$username} 的密码\n";
|
||||||
|
if ($random) {
|
||||||
|
echo "新密码: {$pass}\n";
|
||||||
|
echo "请立刻记下(此密码只在本次输出中显示)\n";
|
||||||
|
}
|
||||||
|
exit(0);
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
fwrite(STDERR, '失败: ' . $e->getMessage() . "\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
208
admin.php
Normal file
208
admin.php
Normal file
|
|
@ -0,0 +1,208 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* 后台管理(加固版)
|
||||||
|
* - 所有写操作(删除/隐藏/回复)改为 POST + CSRF token(原版用 GET 触发删除,可被 CSRF)
|
||||||
|
* - 操作写审计表 admin_logs
|
||||||
|
* - 样式路径用相对路径,部署到子目录也不丢样式
|
||||||
|
*/
|
||||||
|
declare(strict_types=1);
|
||||||
|
require_once __DIR__ . '/config.php';
|
||||||
|
|
||||||
|
check_admin();
|
||||||
|
|
||||||
|
$notice = '';
|
||||||
|
$error = '';
|
||||||
|
|
||||||
|
/* ---------------- 写操作:全部 POST + CSRF ---------------- */
|
||||||
|
if (is_post()) {
|
||||||
|
require_csrf();
|
||||||
|
$action = get_post('action');
|
||||||
|
$id = (int)get_post('id', '0');
|
||||||
|
|
||||||
|
try {
|
||||||
|
$db = get_db();
|
||||||
|
if ($action === 'delete' && $id > 0) {
|
||||||
|
$st = $db->prepare('DELETE FROM messages WHERE id = ?');
|
||||||
|
$st->bindValue(1, $id, SQLITE3_INTEGER);
|
||||||
|
$st->execute();
|
||||||
|
admin_log('delete', $id, '删除留言');
|
||||||
|
$notice = '留言已删除';
|
||||||
|
} elseif ($action === 'toggle_status' && $id > 0) {
|
||||||
|
$q = $db->prepare('SELECT status FROM messages WHERE id = ?');
|
||||||
|
$q->bindValue(1, $id, SQLITE3_INTEGER);
|
||||||
|
$row = $q->execute()->fetchArray(SQLITE3_ASSOC);
|
||||||
|
if ($row) {
|
||||||
|
$new = ((int)$row['status'] === 1) ? 0 : 1;
|
||||||
|
$u = $db->prepare('UPDATE messages SET status = ? WHERE id = ?');
|
||||||
|
$u->bindValue(1, $new, SQLITE3_INTEGER);
|
||||||
|
$u->bindValue(2, $id, SQLITE3_INTEGER);
|
||||||
|
$u->execute();
|
||||||
|
admin_log('toggle_status', $id, '新状态=' . $new);
|
||||||
|
$notice = $new === 1 ? '已显示' : '已隐藏';
|
||||||
|
}
|
||||||
|
} elseif ($action === 'reply' && $id > 0) {
|
||||||
|
$reply = get_post('reply');
|
||||||
|
if (mb_len($reply) > MAX_CONTENT_LEN) {
|
||||||
|
$error = '回复内容过长';
|
||||||
|
} elseif ($reply !== '') {
|
||||||
|
$u = $db->prepare('UPDATE messages SET reply = ?, replied_at = CURRENT_TIMESTAMP WHERE id = ?');
|
||||||
|
$u->bindValue(1, $reply, SQLITE3_TEXT);
|
||||||
|
$u->bindValue(2, $id, SQLITE3_INTEGER);
|
||||||
|
$u->execute();
|
||||||
|
admin_log('reply', $id, '回复留言');
|
||||||
|
$notice = '回复成功';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
log_error('后台操作失败: ' . $e->getMessage());
|
||||||
|
$error = '操作失败,请稍后再试';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 列表 ---------------- */
|
||||||
|
$messages = [];
|
||||||
|
$total_pages = 1;
|
||||||
|
$page = max(1, (int)get_get('page', '1'));
|
||||||
|
try {
|
||||||
|
$db = get_db();
|
||||||
|
$total = (int)$db->querySingle('SELECT COUNT(*) FROM messages');
|
||||||
|
$total_pages = max(1, (int)ceil($total / PAGE_SIZE));
|
||||||
|
if ($page > $total_pages) { $page = $total_pages; }
|
||||||
|
$offset = PAGE_SIZE * ($page - 1);
|
||||||
|
$st = $db->prepare('SELECT * FROM messages ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?');
|
||||||
|
$st->bindValue(1, PAGE_SIZE, SQLITE3_INTEGER);
|
||||||
|
$st->bindValue(2, $offset, SQLITE3_INTEGER);
|
||||||
|
$res = $st->execute();
|
||||||
|
while ($row = $res->fetchArray(SQLITE3_ASSOC)) { $messages[] = $row; }
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
log_error('后台列表读取失败: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>留言管理 - <?= e(SITE_NAME) ?></title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
<style>
|
||||||
|
.admin-nav { margin-bottom: 20px; padding: 10px; background: #fff; border-radius: 4px; }
|
||||||
|
.admin-nav a { color: #2196f3; text-decoration: none; margin-right: 15px; }
|
||||||
|
.status-badge { padding: 2px 8px; border-radius: 4px; font-size: 12px; }
|
||||||
|
.status-visible { background: #4caf50; color: white; }
|
||||||
|
.status-hidden { background: #f44336; color: white; }
|
||||||
|
.message-card { margin-bottom: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 8px; background: #fafafa; }
|
||||||
|
.message-card .reply { background: #e3f2fd; padding: 10px; margin-top: 10px; border-radius: 4px; border-left: 3px solid #2196f3; }
|
||||||
|
.actions { margin-top: 10px; }
|
||||||
|
.actions button, .actions a.btn { margin-right: 5px; padding: 5px 10px; cursor: pointer; border: none; border-radius: 4px; text-decoration: none; display: inline-block; font-size: 14px; }
|
||||||
|
.btn-hide { background: #f44336; color: white; }
|
||||||
|
.btn-show { background: #4caf50; color: white; }
|
||||||
|
.btn-delete { background: #2196f3; color: white; }
|
||||||
|
.btn-reply { background: #ff9800; color: white; }
|
||||||
|
.logout-form { display: inline; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<header>
|
||||||
|
<h1>留言管理后台</h1>
|
||||||
|
<div class="admin-nav">
|
||||||
|
<a href="admin.php">所有留言</a>
|
||||||
|
<a href="index.php">返回前台</a>
|
||||||
|
<a href="https://zhangpu.dev/">zhangpu.dev</a>
|
||||||
|
<form method="POST" action="logout.php" class="logout-form">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<button type="submit" style="background:none;border:none;color:#f44336;cursor:pointer;">退出登录</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<?php if ($notice !== ''): ?><div class="success"><?= e($notice) ?></div><?php endif; ?>
|
||||||
|
<?php if ($error !== ''): ?><div class="error"><?= e($error) ?></div><?php endif; ?>
|
||||||
|
|
||||||
|
<?php if (!$messages): ?>
|
||||||
|
<div class="no-messages">暂无留言</div>
|
||||||
|
<?php else: ?>
|
||||||
|
<?php foreach ($messages as $msg): ?>
|
||||||
|
<div class="message-card">
|
||||||
|
<div class="message-header">
|
||||||
|
<strong class="name"><?= e($msg['name']) ?></strong>
|
||||||
|
<?php if (!empty($msg['email'])): ?>
|
||||||
|
<span class="email">(<?= e($msg['email']) ?>)</span>
|
||||||
|
<?php endif; ?>
|
||||||
|
<span class="time"><?= e(date('Y-m-d H:i', strtotime((string)$msg['created_at']))) ?></span>
|
||||||
|
<span class="ip">IP: <?= e($msg['ip_address']) ?></span>
|
||||||
|
<span class="status-badge <?= ((int)$msg['status'] === 1) ? 'status-visible' : 'status-hidden' ?>">
|
||||||
|
<?= ((int)$msg['status'] === 1) ? '显示' : '隐藏' ?>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="content"><?= nl2br(e($msg['content'])) ?></div>
|
||||||
|
|
||||||
|
<?php if (!empty($msg['reply'])): ?>
|
||||||
|
<div class="reply">
|
||||||
|
<strong>管理员回复:</strong>
|
||||||
|
<?= nl2br(e($msg['reply'])) ?>
|
||||||
|
<?php if (!empty($msg['replied_at'])): ?>
|
||||||
|
<span class="reply-time">(<?= e(date('Y-m-d H:i', strtotime((string)$msg['replied_at']))) ?>)</span>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
<form method="POST" action="admin.php" style="display:inline;">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="id" value="<?= (int)$msg['id'] ?>">
|
||||||
|
<input type="hidden" name="action" value="toggle_status">
|
||||||
|
<button type="submit" class="btn <?= ((int)$msg['status'] === 1) ? 'btn-hide' : 'btn-show' ?>">
|
||||||
|
<?= ((int)$msg['status'] === 1) ? '隐藏' : '显示' ?>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form method="POST" action="admin.php" style="display:inline;">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="id" value="<?= (int)$msg['id'] ?>">
|
||||||
|
<input type="hidden" name="action" value="delete">
|
||||||
|
<button type="submit" class="btn btn-delete"
|
||||||
|
onclick="return confirm('确定删除这条留言?删除后不可恢复。');">删除</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<button type="button" class="btn btn-reply" onclick="toggleReply(<?= (int)$msg['id'] ?>)">回复</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="reply-form-<?= (int)$msg['id'] ?>" class="reply-form" style="display:none; margin-top:15px; padding:10px; border:1px solid #ddd; border-radius:4px;">
|
||||||
|
<form method="POST" action="admin.php">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="id" value="<?= (int)$msg['id'] ?>">
|
||||||
|
<input type="hidden" name="action" value="reply">
|
||||||
|
<textarea name="reply" rows="3" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;" maxlength="<?= MAX_CONTENT_LEN ?>"><?= e($msg['reply'] ?? '') ?></textarea>
|
||||||
|
<div style="margin-top:10px;">
|
||||||
|
<button type="submit" class="btn" style="background:#4caf50;">保存回复</button>
|
||||||
|
<button type="button" class="btn" onclick="toggleReply(<?= (int)$msg['id'] ?>)">取消</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<?php if ($total_pages > 1): ?>
|
||||||
|
<div class="pagination" style="margin-top:20px; text-align:center;">
|
||||||
|
<span>第 <?= (int)$page ?> / <?= (int)$total_pages ?> 页</span>
|
||||||
|
<?php if ($page > 1): ?><a href="?page=<?= (int)$page - 1 ?>">< 上一页</a><?php endif; ?>
|
||||||
|
<?php if ($page < $total_pages): ?><a href="?page=<?= (int)$page + 1 ?>">下一页 ></a><?php endif; ?>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer><p>© <?= date('Y') ?> <?= e(SITE_NAME) ?> 管理后台</p></footer>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
function toggleReply(id) {
|
||||||
|
var form = document.getElementById('reply-form-' + id);
|
||||||
|
if (form) { form.style.display = (form.style.display === 'none') ? 'block' : 'none'; }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
18
assets/script.js
Normal file
18
assets/script.js
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
// 前端轻量校验(服务端已做同样校验,前端只是提示)
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
var form = document.querySelector('.guestbook-form');
|
||||||
|
if (!form) { return; }
|
||||||
|
form.addEventListener('submit', function (e) {
|
||||||
|
var content = document.getElementById('content');
|
||||||
|
var name = document.getElementById('name');
|
||||||
|
if (content && content.value.trim().length < 5) {
|
||||||
|
e.preventDefault();
|
||||||
|
alert('留言内容至少需要 5 个字符');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (name && name.value.trim() === '') {
|
||||||
|
e.preventDefault();
|
||||||
|
alert('请输入姓名');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
307
assets/style.css
Normal file
307
assets/style.css
Normal file
|
|
@ -0,0 +1,307 @@
|
||||||
|
/* 全局样式 */
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif;
|
||||||
|
background: #f5f5f5;
|
||||||
|
color: #333;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
max-width: 1200px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
header {
|
||||||
|
background: #2196f3;
|
||||||
|
color: white;
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
header h1 {
|
||||||
|
font-size: 1.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
header nav a {
|
||||||
|
color: white;
|
||||||
|
text-decoration: none;
|
||||||
|
margin-left: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
header nav a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 表单样式 */
|
||||||
|
.form-section {
|
||||||
|
background: white;
|
||||||
|
padding: 25px;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-bottom: 15px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input,
|
||||||
|
.form-group textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group textarea {
|
||||||
|
resize: vertical;
|
||||||
|
min-height: 100px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 按钮样式 */
|
||||||
|
.btn {
|
||||||
|
padding: 10px 20px;
|
||||||
|
background: #2196f3;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
transition: background 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:hover {
|
||||||
|
background: #1976d2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.success {
|
||||||
|
background: #d4edda;
|
||||||
|
color: #155724;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
border: 1px solid #c3e6cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background: #f8d7da;
|
||||||
|
color: #721c24;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
border: 1px solid #f5c6cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 留言卡片样式 */
|
||||||
|
.messages-section {
|
||||||
|
background: white;
|
||||||
|
padding: 25px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages-section h2 {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-messages {
|
||||||
|
text-align: center;
|
||||||
|
padding: 40px;
|
||||||
|
color: #999;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-card {
|
||||||
|
background: #fafafa;
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
border: 1px solid #eee;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header .name {
|
||||||
|
font-size: 1.1em;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header .email {
|
||||||
|
color: #666;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header .time {
|
||||||
|
color: #999;
|
||||||
|
font-size: 0.85em;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header .ip {
|
||||||
|
color: #aaa;
|
||||||
|
font-size: 0.8em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header .status-badge {
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-visible {
|
||||||
|
background: #4caf50;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-hidden {
|
||||||
|
background: #f44336;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-wrap: break-word;
|
||||||
|
color: #444;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reply {
|
||||||
|
background: #e3f2fd;
|
||||||
|
padding: 10px 15px;
|
||||||
|
margin-top: 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
border-left: 3px solid #2196f3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reply strong {
|
||||||
|
color: #1565c0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
margin-top: 15px;
|
||||||
|
display: flex;
|
||||||
|
gap: 5px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 分页样式 */
|
||||||
|
.pagination {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
margin-top: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination a {
|
||||||
|
padding: 8px 16px;
|
||||||
|
background: white;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
text-decoration: none;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination a:hover {
|
||||||
|
background: #f5f5f5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination span {
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 登录页面 */
|
||||||
|
.login-container {
|
||||||
|
max-width: 400px;
|
||||||
|
margin: 100px auto;
|
||||||
|
background: white;
|
||||||
|
padding: 30px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form .form-group {
|
||||||
|
margin-bottom: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 后台管理 */
|
||||||
|
.admin-nav {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
padding: 10px;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-nav a {
|
||||||
|
color: #2196f3;
|
||||||
|
text-decoration: none;
|
||||||
|
margin-right: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 响应式 */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
header {
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
header h1 {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header .time {
|
||||||
|
margin-left: 0;
|
||||||
|
margin-top: 5px;
|
||||||
|
}
|
||||||
|
}
|
||||||
267
config.php
Normal file
267
config.php
Normal file
|
|
@ -0,0 +1,267 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* 留言系统配置 + 工具函数(加固版 2026-10-30)
|
||||||
|
* ------------------------------------------------------------------
|
||||||
|
* 相比原版修掉的问题:
|
||||||
|
* 1. 数据文件默认放【webroot 外】(dirname(__DIR__)/guestbook-data/guestbook.db),杜绝 .db 被下载
|
||||||
|
* 2. 首次访问自动建表(原版不建表,直接 500),并自动初始化管理员(随机密码,不再硬编码 admin123)
|
||||||
|
* 3. 会话加固:Secure/HttpOnly/SameSite + use_strict_mode + 登录后换 SID + 真正的会话超时
|
||||||
|
* 4. 所有写操作走 POST + CSRF token(原版删除/隐藏用 GET,等于把删除做成可被 CSRF 触发)
|
||||||
|
* 5. 留言提交/登录加频率限制(防灌水、防爆破)
|
||||||
|
* 6. 异常信息不再吐给访客(统一写日志,前台只给友好提示)
|
||||||
|
* 7. mbstring 缺失时不再致命(带 fallback)
|
||||||
|
* 8. 前台不再公开显示留言人邮箱;后台显示 IP 属内部信息
|
||||||
|
* 9. 加安全响应头(X-Frame-Options / X-Content-Type-Options / CSP)
|
||||||
|
*
|
||||||
|
* 可选:本文件不写死任何密码。优先级
|
||||||
|
* 环境变量 GUESTBOOK_ADMIN_USER / GUESTBOOK_ADMIN_PASS > 首次运行随机生成(密码写到站外 data 目录)
|
||||||
|
*/
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/* ---------------- 路径与常量 ---------------- */
|
||||||
|
define('GUESTBOOK_ROOT', __DIR__);
|
||||||
|
define('GUESTBOOK_BASE', rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/'));
|
||||||
|
|
||||||
|
/** 数据目录:默认在 webroot 之外(与站点目录同级) */
|
||||||
|
// 数据目录必须在 webroot 之外:__DIR__ = <site>/public/guestbook → 两级 up = <site>
|
||||||
|
$gbDataDir = getenv('GUESTBOOK_DATA_DIR') ?: (dirname(dirname(__DIR__)) . '/guestbook-data');
|
||||||
|
if (!is_dir($gbDataDir)) { @mkdir($gbDataDir, 0750, true); }
|
||||||
|
define('GUESTBOOK_DATA_DIR', $gbDataDir);
|
||||||
|
define('DB_PATH', getenv('GUESTBOOK_DB') ?: ($gbDataDir . '/guestbook.db'));
|
||||||
|
|
||||||
|
define('SITE_NAME', '在线留言系统');
|
||||||
|
define('PAGE_SIZE', 10);
|
||||||
|
define('SESSION_TIMEOUT', 7200); // 2 小时
|
||||||
|
define('RATE_LIMIT_MESSAGE', 5); // 每 IP 每 10 分钟最多 5 条留言
|
||||||
|
define('RATE_LIMIT_MESSAGE_WINDOW', 600);
|
||||||
|
define('RATE_LIMIT_LOGIN', 10); // 每 IP 每 10 分钟最多 10 次登录尝试
|
||||||
|
define('RATE_LIMIT_LOGIN_WINDOW', 600);
|
||||||
|
define('MAX_NAME_LEN', 50);
|
||||||
|
define('MAX_EMAIL_LEN', 100);
|
||||||
|
define('MAX_CONTENT_LEN', 1000);
|
||||||
|
define('MIN_CONTENT_LEN', 5);
|
||||||
|
|
||||||
|
/* ---------------- 会话安全 ---------------- */
|
||||||
|
ini_set('session.use_strict_mode', '1');
|
||||||
|
ini_set('session.use_only_cookies', '1');
|
||||||
|
ini_set('session.gc_maxlifetime', (string)SESSION_TIMEOUT);
|
||||||
|
if (session_status() === PHP_SESSION_NONE) {
|
||||||
|
session_set_cookie_params([
|
||||||
|
'lifetime' => 0,
|
||||||
|
'path' => '/',
|
||||||
|
'domain' => '',
|
||||||
|
'secure' => (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off'),
|
||||||
|
'httponly' => true,
|
||||||
|
'samesite' => 'Lax',
|
||||||
|
]);
|
||||||
|
session_start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 基础工具 ---------------- */
|
||||||
|
function e($str): string {
|
||||||
|
return htmlspecialchars((string)$str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||||
|
}
|
||||||
|
function mb_len(string $s): int {
|
||||||
|
return function_exists('mb_strlen') ? mb_strlen($s, 'UTF-8') : strlen($s);
|
||||||
|
}
|
||||||
|
function mb_cut(string $s, int $n): string {
|
||||||
|
if (function_exists('mb_substr')) { return mb_substr($s, 0, $n, 'UTF-8'); }
|
||||||
|
if (preg_match('/^(.{0,' . $n . '})/us', $s, $m)) { return $m[1]; }
|
||||||
|
return substr($s, 0, $n);
|
||||||
|
}
|
||||||
|
function get_post(string $key, string $default = ''): string {
|
||||||
|
return isset($_POST[$key]) ? trim((string)$_POST[$key]) : $default;
|
||||||
|
}
|
||||||
|
function get_get(string $key, string $default = ''): string {
|
||||||
|
return isset($_GET[$key]) ? trim((string)$_GET[$key]) : $default;
|
||||||
|
}
|
||||||
|
function is_post(): bool {
|
||||||
|
return ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST';
|
||||||
|
}
|
||||||
|
function client_ip(): string {
|
||||||
|
return (string)($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
|
||||||
|
}
|
||||||
|
function log_error(string $msg): void {
|
||||||
|
@error_log('[guestbook] ' . $msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 安全响应头 ---------------- */
|
||||||
|
if (!headers_sent()) {
|
||||||
|
header('X-Content-Type-Options: nosniff');
|
||||||
|
header('X-Frame-Options: SAMEORIGIN');
|
||||||
|
header('Referrer-Policy: strict-origin-when-cross-origin');
|
||||||
|
header("Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; form-action 'self'; frame-ancestors 'self'");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 数据库 ---------------- */
|
||||||
|
function get_db(): SQLite3 {
|
||||||
|
static $db = null;
|
||||||
|
if ($db === null) {
|
||||||
|
if (!is_dir(dirname(DB_PATH))) { @mkdir(dirname(DB_PATH), 0750, true); }
|
||||||
|
$db = new SQLite3(DB_PATH);
|
||||||
|
$db->enableExceptions(true);
|
||||||
|
$db->exec('PRAGMA journal_mode = WAL;');
|
||||||
|
$db->exec('PRAGMA busy_timeout = 3000;');
|
||||||
|
$db->exec('PRAGMA foreign_keys = ON;');
|
||||||
|
ensure_schema($db);
|
||||||
|
ensure_admin($db);
|
||||||
|
}
|
||||||
|
return $db;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 自动建表(原版不会建表 → 新部署直接 500) */
|
||||||
|
function ensure_schema(SQLite3 $db): void {
|
||||||
|
$db->exec("CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
email TEXT,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
ip_address TEXT,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
status INTEGER DEFAULT 1,
|
||||||
|
reply TEXT,
|
||||||
|
replied_at DATETIME
|
||||||
|
)");
|
||||||
|
$db->exec("CREATE TABLE IF NOT EXISTS admins (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT UNIQUE NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)");
|
||||||
|
$db->exec("CREATE TABLE IF NOT EXISTS admin_logs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
admin_user TEXT,
|
||||||
|
action TEXT,
|
||||||
|
target_id INTEGER,
|
||||||
|
detail TEXT,
|
||||||
|
ip TEXT,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)");
|
||||||
|
$db->exec("CREATE TABLE IF NOT EXISTS rate_limits (
|
||||||
|
rk TEXT PRIMARY KEY,
|
||||||
|
cnt INTEGER DEFAULT 0,
|
||||||
|
win_start INTEGER
|
||||||
|
)");
|
||||||
|
$db->exec("CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at DESC)");
|
||||||
|
$db->exec("CREATE INDEX IF NOT EXISTS idx_messages_status ON messages(status)");
|
||||||
|
$db->exec("CREATE INDEX IF NOT EXISTS idx_admin_logs_created ON admin_logs(created_at DESC)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 初始化管理员:优先环境变量,其次随机生成(不再有 admin/admin123 这种公开默认口令) */
|
||||||
|
function ensure_admin(SQLite3 $db): void {
|
||||||
|
$cnt = (int)$db->querySingle("SELECT COUNT(*) FROM admins");
|
||||||
|
if ($cnt > 0) { return; }
|
||||||
|
|
||||||
|
$user = getenv('GUESTBOOK_ADMIN_USER') ?: 'admin';
|
||||||
|
$pass = getenv('GUESTBOOK_ADMIN_PASS') ?: '';
|
||||||
|
$generated = false;
|
||||||
|
if ($pass === '') {
|
||||||
|
$pass = bin2hex(random_bytes(8)); // 16 位随机十六进制
|
||||||
|
$generated = true;
|
||||||
|
}
|
||||||
|
$hash = password_hash($pass, PASSWORD_DEFAULT);
|
||||||
|
$st = $db->prepare('INSERT INTO admins (username, password_hash) VALUES (?, ?)');
|
||||||
|
$st->bindValue(1, $user, SQLITE3_TEXT);
|
||||||
|
$st->bindValue(2, $hash, SQLITE3_TEXT);
|
||||||
|
$st->execute();
|
||||||
|
|
||||||
|
if ($generated) {
|
||||||
|
// 密码只写站外文件(600),需要 SSH 上去看;看完请删除
|
||||||
|
$f = GUESTBOOK_DATA_DIR . '/initial-admin-password.txt';
|
||||||
|
@file_put_contents($f, "初始管理员账号: {$user}\n初始管理员密码: {$pass}\n生成时间: " . date('c') . "\n(看到后请删除本文件)\n");
|
||||||
|
@chmod($f, 0600);
|
||||||
|
log_error("已生成初始管理员账号 {$user},随机密码已写入 {$f}");
|
||||||
|
}
|
||||||
|
log_error("管理员账号已初始化: {$user}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- CSRF ---------------- */
|
||||||
|
function csrf_token(): string {
|
||||||
|
if (empty($_SESSION['csrf_token'])) {
|
||||||
|
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
||||||
|
}
|
||||||
|
return (string)$_SESSION['csrf_token'];
|
||||||
|
}
|
||||||
|
function csrf_field(): string {
|
||||||
|
return '<input type="hidden" name="csrf_token" value="' . e(csrf_token()) . '">';
|
||||||
|
}
|
||||||
|
function csrf_check(): bool {
|
||||||
|
$t = (string)($_POST['csrf_token'] ?? '');
|
||||||
|
return !empty($_SESSION['csrf_token']) && $t !== '' && hash_equals((string)$_SESSION['csrf_token'], $t);
|
||||||
|
}
|
||||||
|
function require_csrf(): void {
|
||||||
|
if (!csrf_check()) {
|
||||||
|
log_error('CSRF 校验失败 ip=' . client_ip());
|
||||||
|
http_response_code(403);
|
||||||
|
header('Content-Type: text/html; charset=utf-8');
|
||||||
|
echo '<!DOCTYPE html><meta charset="utf-8"><p>请求已失效(CSRF 校验失败),请刷新页面重试。</p>';
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 频率限制 ---------------- */
|
||||||
|
function rate_limit(string $key, int $limit, int $window): bool {
|
||||||
|
try {
|
||||||
|
$db = get_db();
|
||||||
|
$now = time();
|
||||||
|
$db->exec('BEGIN IMMEDIATE');
|
||||||
|
$st = $db->prepare('SELECT cnt, win_start FROM rate_limits WHERE rk = ?');
|
||||||
|
$st->bindValue(1, $key, SQLITE3_TEXT);
|
||||||
|
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);
|
||||||
|
if (!$row || ((int)$row['win_start'] + $window) < $now) {
|
||||||
|
$up = $db->prepare('INSERT INTO rate_limits (rk, cnt, win_start) VALUES (?, 1, ?) ON CONFLICT(rk) DO UPDATE SET cnt = 1, win_start = excluded.win_start');
|
||||||
|
$up->bindValue(1, $key, SQLITE3_TEXT);
|
||||||
|
$up->bindValue(2, $now, SQLITE3_INTEGER);
|
||||||
|
$up->execute();
|
||||||
|
$db->exec('COMMIT');
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
$cnt = (int)$row['cnt'] + 1;
|
||||||
|
$up = $db->prepare('UPDATE rate_limits SET cnt = ? WHERE rk = ?');
|
||||||
|
$up->bindValue(1, $cnt, SQLITE3_INTEGER);
|
||||||
|
$up->bindValue(2, $key, SQLITE3_TEXT);
|
||||||
|
$up->execute();
|
||||||
|
$db->exec('COMMIT');
|
||||||
|
return $cnt <= $limit;
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
log_error('rate_limit 异常: ' . $e->getMessage());
|
||||||
|
return true; // 限流器坏掉时不要把整个站点拖死
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 管理员鉴权 ---------------- */
|
||||||
|
function check_admin(): void {
|
||||||
|
if (empty($_SESSION['admin_logged_in'])) {
|
||||||
|
header('Location: login.php');
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
// 会话超时
|
||||||
|
if (!empty($_SESSION['login_time']) && (time() - (int)$_SESSION['login_time']) > SESSION_TIMEOUT) {
|
||||||
|
$_SESSION = [];
|
||||||
|
session_destroy();
|
||||||
|
header('Location: login.php?timeout=1');
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function admin_log(string $action, ?int $targetId, string $detail = ''): void {
|
||||||
|
try {
|
||||||
|
$db = get_db();
|
||||||
|
$st = $db->prepare('INSERT INTO admin_logs (admin_user, action, target_id, detail, ip) VALUES (?, ?, ?, ?, ?)');
|
||||||
|
$st->bindValue(1, (string)($_SESSION['admin_username'] ?? 'unknown'), SQLITE3_TEXT);
|
||||||
|
$st->bindValue(2, $action, SQLITE3_TEXT);
|
||||||
|
$st->bindValue(3, $targetId, SQLITE3_INTEGER);
|
||||||
|
$st->bindValue(4, mb_cut($detail, 200), SQLITE3_TEXT);
|
||||||
|
$st->bindValue(5, client_ip(), SQLITE3_TEXT);
|
||||||
|
$st->execute();
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
log_error('admin_log 失败: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 错误输出(不泄露内部细节) ---------------- */
|
||||||
|
function error_out(string $msg, int $code = 400): void {
|
||||||
|
http_response_code($code);
|
||||||
|
header('Content-Type: text/html; charset=utf-8');
|
||||||
|
echo '<!DOCTYPE html><meta charset="utf-8"><title>出错了</title><p style="font-family:sans-serif">' . e($msg) . '</p>';
|
||||||
|
exit;
|
||||||
|
}
|
||||||
41
db.sql
Normal file
41
db.sql
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
-- 留言系统数据库结构(参考用;程序首次运行会自动建表,通常不需要手工执行)
|
||||||
|
-- 手工执行方式: sqlite3 <数据目录>/guestbook.db < db.sql
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
email TEXT,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
ip_address TEXT,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
status INTEGER DEFAULT 1, -- 0=隐藏 1=显示
|
||||||
|
reply TEXT,
|
||||||
|
replied_at DATETIME
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS admins (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT UNIQUE NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS admin_logs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
admin_user TEXT,
|
||||||
|
action TEXT,
|
||||||
|
target_id INTEGER,
|
||||||
|
detail TEXT,
|
||||||
|
ip TEXT,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS rate_limits (
|
||||||
|
rk TEXT PRIMARY KEY,
|
||||||
|
cnt INTEGER DEFAULT 0,
|
||||||
|
win_start INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_status ON messages(status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_admin_logs_created ON admin_logs(created_at DESC);
|
||||||
120
docs/部署说明.md
Normal file
120
docs/部署说明.md
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
# 留言系统(guestbook)部署说明 · 加固版 2026-10-30
|
||||||
|
|
||||||
|
## 0. 这版修掉了什么
|
||||||
|
|
||||||
|
| # | 原版问题 | 本版做法 |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | **全新部署直接 500**(config.php 从不建表,说明文档谎称"自动初始化") | 首次运行自动建表(messages / admins / admin_logs / rate_limits + 索引) |
|
||||||
|
| 2 | **管理员弱口令 admin/admin123 明文硬编码** | 首次运行生成 16 位随机密码,写到**站外** `guestbook-data/initial-admin-password.txt`(600);也支持环境变量 `GUESTBOOK_ADMIN_USER` / `GUESTBOOK_ADMIN_PASS` |
|
||||||
|
| 3 | config.php 里哈希常量用双引号 → PHP 变量插值告警 | 该死代码已删除 |
|
||||||
|
| 4 | **删除/隐藏留言走 GET、无 CSRF**(实测 `GET admin.php?delete=1` 直接删库) | 全部改 POST + CSRF token;删除/隐藏/回复都记审计日志 |
|
||||||
|
| 5 | **SQLite 在 webroot 内**,靠 `.htaccess` 保护 —— 但 **nginx 不读 .htaccess** | 数据默认放 **webroot 外**(`../guestbook-data/guestbook.db`),并附 nginx 封堵规则 |
|
||||||
|
| 6 | 会话 cookie 无 Secure/HttpOnly/SameSite、登录不换 SID、`SESSION_TIMEOUT` 是死代码 | 全部落实 + 登录后 `session_regenerate_id(true)` + 2 小时会话超时 |
|
||||||
|
| 7 | 异常信息直接吐给访客(含 DB 路径) | 内部异常只写日志,前台给友好提示 |
|
||||||
|
| 8 | 无限流(灌水 / 登录爆破) | 留言 5 条/10 分钟/IP、登录 10 次/10 分钟/IP(DB 计数) |
|
||||||
|
| 9 | 前台公开显示留言人**邮箱** | 前台不显示邮箱,只在后台显示 |
|
||||||
|
| 10 | 硬依赖 mbstring,缺了就 500 | `mb_len()/mb_cut()` 带 fallback |
|
||||||
|
| 11 | admin/login 的 CSS 写 `../assets/`,部署到子目录样式全丢 | 改用相对路径 `assets/style.css` |
|
||||||
|
| 12 | 留言页写"正在审核中"但实际立即公开 | 文案与逻辑对齐(status 默认 1=公开;可后台隐藏) |
|
||||||
|
|
||||||
|
另外新增:安全响应头(X-Frame-Options / X-Content-Type-Options / CSP / Referrer-Policy)、审计表 `admin_logs`、命令行改密工具 `admin-password.php`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 部署步骤
|
||||||
|
|
||||||
|
假设站点根目录是 `/opt/1panel/www/sites/<域名>/index`,留言本放 `index/guestbook/`。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1) 上传(本目录全部文件)到 index/guestbook/
|
||||||
|
# 2) 建站外数据目录并给 php-fpm 用户权限
|
||||||
|
cd /opt/1panel/www/sites/<域名>/
|
||||||
|
mkdir -p guestbook-data
|
||||||
|
chown www-data:www-data guestbook-data # 换成你实际的 php-fpm 运行用户
|
||||||
|
chmod 750 guestbook-data
|
||||||
|
|
||||||
|
# 3) 首次访问会自动建表并生成初始管理员密码
|
||||||
|
# (也可以命令行预热:cd index/guestbook && php admin-password.php --random)
|
||||||
|
|
||||||
|
# 4) SSH 上去拿初始密码
|
||||||
|
cat /opt/1panel/www/sites/<域名>/guestbook-data/initial-admin-password.txt
|
||||||
|
|
||||||
|
# 5) 登录后台后(或命令行)改成自己的密码,然后删掉密码文件
|
||||||
|
cd /opt/1panel/www/sites/<域名>/index/guestbook
|
||||||
|
php admin-password.php '你的新密码'
|
||||||
|
rm -f ../guestbook-data/initial-admin-password.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
**PHP 要求**:PHP 7.4+(8.x 更稳),需 `sqlite3` + `pdo_sqlite`;`mbstring` 有则更好(没有也能跑);`openssl` 用于随机密码。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. nginx 配置(必须配,nginx 不读 .htaccess)
|
||||||
|
|
||||||
|
在站点的 `server {}` 里加:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
# ---- 留言系统加固规则 ----
|
||||||
|
# 1) 数据库/日志/密钥类文件一律封死
|
||||||
|
location ~* \.(db|sqlite|sql|log|ini|pem|key|bak|old|orig|swp)$ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
# 2) 数据目录(若仍放在 webroot 内)
|
||||||
|
location ^~ /guestbook/data/ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
# 3) 留言本里的敏感文件
|
||||||
|
location ~* ^/guestbook/(db\.sql|initial-admin-password\.txt|.*\.md)$ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
# 4) 备份/压缩包类
|
||||||
|
location ~* \.(tar|gz|zip|7z|rar)$ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
配完执行 `nginx -t` 通过再 `nginx -s reload`。
|
||||||
|
|
||||||
|
> ⚠️ 已有 `location ~* \.(bak|db|pem|key|...)` 规则的站点无需重复加第 1 条,检查一下有没有就行。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 验收清单(部署完跑一遍)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
D=https://你的域名/guestbook
|
||||||
|
|
||||||
|
# 前台正常
|
||||||
|
curl -s -o /dev/null -w "index.php %{http_code}\n" $D/index.php # 期望 200
|
||||||
|
curl -s -o /dev/null -w "login.php %{http_code}\n" $D/login.php # 期望 200
|
||||||
|
curl -s -o /dev/null -w "admin.php %{http_code}\n" $D/admin.php # 期望 302(跳登录)
|
||||||
|
|
||||||
|
# 敏感文件取不到
|
||||||
|
curl -s -o /dev/null -w "guestbook.db %{http_code}\n" $D/guestbook.db # 期望 404
|
||||||
|
curl -s -o /dev/null -w "db.sql %{http_code}\n" $D/db.sql # 期望 404
|
||||||
|
curl -s -o /dev/null -w "data/ %{http_code}\n" $D/data/ # 期望 404
|
||||||
|
curl -s -o /dev/null -w "初始密码文件 %{http_code}\n" $D/initial-admin-password.txt # 期望 404
|
||||||
|
|
||||||
|
# CSRF 生效:没有 token 的 POST 必须被拒
|
||||||
|
curl -s -o /dev/null -w "无token留言 %{http_code}\n" -X POST $D/index.php \
|
||||||
|
-d "name=x&content=abcdefgh&submit=1" # 期望 403
|
||||||
|
|
||||||
|
# GET 不能删数据
|
||||||
|
curl -s -o /dev/null -w "GET删除 %{http_code}\n" $D/admin.php?delete=1 # 期望 302(未登录)/ 不删数据
|
||||||
|
```
|
||||||
|
|
||||||
|
浏览器再确认:提交留言 → 出现在列表 → 后台能回复/隐藏/删除 → 退出登录。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 常见坑
|
||||||
|
|
||||||
|
1. **nginx 不读 .htaccess** → `.htaccess` 只是给 Apache 的,nginx 必须自己写规则(见第 2 节)。
|
||||||
|
2. **数据目录权限** → php-fpm 用户写不了 `guestbook-data` 就会建表失败(表现为 500 或"留言提交失败"),先 `chown`。
|
||||||
|
3. **open_basedir** → 部分主机会限制 PHP 只能访问站点目录;本版数据目录在站点目录**外**,若报"open_basedir 限制",要么把 `GUESTBOOK_DATA_DIR` 指回站点内(并配 nginx 封 data/),要么放开 open_basedir。
|
||||||
|
4. **初始密码文件** → 看完立刻删,别留在服务器上。
|
||||||
|
5. **别把留言本和收银数据库放同一个库** → 独立 SQLite 文件,互不影响。
|
||||||
158
index.php
Normal file
158
index.php
Normal file
|
|
@ -0,0 +1,158 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* 前台:留言表单 + 留言列表(加固版)
|
||||||
|
*/
|
||||||
|
declare(strict_types=1);
|
||||||
|
require_once __DIR__ . '/config.php';
|
||||||
|
|
||||||
|
$message_sent = false;
|
||||||
|
$form_error = '';
|
||||||
|
$name = $email = $content = '';
|
||||||
|
|
||||||
|
if (is_post()) {
|
||||||
|
require_csrf(); // 原版没有 CSRF
|
||||||
|
$name = get_post('name');
|
||||||
|
$email = get_post('email');
|
||||||
|
$content = get_post('content');
|
||||||
|
|
||||||
|
if ($name === '') {
|
||||||
|
$form_error = '请输入姓名';
|
||||||
|
} elseif (mb_len($name) > MAX_NAME_LEN) {
|
||||||
|
$form_error = '姓名不能超过 ' . MAX_NAME_LEN . ' 个字符';
|
||||||
|
} elseif ($content === '') {
|
||||||
|
$form_error = '请输入留言内容';
|
||||||
|
} elseif (mb_len($content) < MIN_CONTENT_LEN) {
|
||||||
|
$form_error = '留言内容至少 ' . MIN_CONTENT_LEN . ' 个字符';
|
||||||
|
} elseif (mb_len($content) > MAX_CONTENT_LEN) {
|
||||||
|
$form_error = '留言内容不能超过 ' . MAX_CONTENT_LEN . ' 个字符';
|
||||||
|
} elseif ($email !== '' && (mb_len($email) > MAX_EMAIL_LEN || !filter_var($email, FILTER_VALIDATE_EMAIL))) {
|
||||||
|
$form_error = '邮箱格式不正确';
|
||||||
|
} elseif (!rate_limit('msg:' . client_ip(), RATE_LIMIT_MESSAGE, RATE_LIMIT_MESSAGE_WINDOW)) {
|
||||||
|
$form_error = '提交太频繁,请稍后再试';
|
||||||
|
log_error('留言限流触发 ip=' . client_ip());
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
$db = get_db();
|
||||||
|
$st = $db->prepare('INSERT INTO messages (name, email, content, ip_address, status) VALUES (?, ?, ?, ?, 1)');
|
||||||
|
$st->bindValue(1, $name, SQLITE3_TEXT);
|
||||||
|
$st->bindValue(2, $email !== '' ? $email : null, SQLITE3_TEXT);
|
||||||
|
$st->bindValue(3, $content, SQLITE3_TEXT);
|
||||||
|
$st->bindValue(4, client_ip(), SQLITE3_TEXT);
|
||||||
|
$st->execute();
|
||||||
|
$message_sent = true;
|
||||||
|
$name = $email = $content = '';
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
log_error('留言写入失败: ' . $e->getMessage());
|
||||||
|
$form_error = '提交失败,请稍后再试'; // 不给访客看内部异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 列表 */
|
||||||
|
$messages = [];
|
||||||
|
$total_pages = 1;
|
||||||
|
$page = max(1, (int)get_get('page', '1'));
|
||||||
|
try {
|
||||||
|
$db = get_db();
|
||||||
|
$total = (int)$db->querySingle('SELECT COUNT(*) FROM messages WHERE status = 1');
|
||||||
|
$total_pages = max(1, (int)ceil($total / PAGE_SIZE));
|
||||||
|
if ($page > $total_pages) { $page = $total_pages; }
|
||||||
|
$offset = PAGE_SIZE * ($page - 1);
|
||||||
|
// 注意:必须带上 reply / replied_at,否则前台不显示管理员回复(2026-10-30 修)
|
||||||
|
$st = $db->prepare('SELECT id, name, content, created_at, reply, replied_at FROM messages WHERE status = 1 ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?');
|
||||||
|
$st->bindValue(1, PAGE_SIZE, SQLITE3_INTEGER);
|
||||||
|
$st->bindValue(2, $offset, SQLITE3_INTEGER);
|
||||||
|
$res = $st->execute();
|
||||||
|
while ($row = $res->fetchArray(SQLITE3_ASSOC)) { $messages[] = $row; }
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
log_error('留言列表读取失败: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title><?= e(SITE_NAME) ?></title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<header>
|
||||||
|
<h1><?= e(SITE_NAME) ?></h1>
|
||||||
|
<nav>
|
||||||
|
<a href="index.php">首页</a>
|
||||||
|
<a href="https://zhangpu.dev/">zhangpu.dev</a>
|
||||||
|
<a href="login.php">管理</a>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<section class="form-section">
|
||||||
|
<h2>发表留言</h2>
|
||||||
|
<?php if ($message_sent): ?>
|
||||||
|
<div class="success">恭喜!您的留言已成功提交。</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php if ($form_error !== ''): ?>
|
||||||
|
<div class="error"><?= e($form_error) ?></div>
|
||||||
|
<?php endif; ?>
|
||||||
|
<form method="POST" action="index.php" class="guestbook-form">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="name">姓名 *:</label>
|
||||||
|
<input type="text" id="name" name="name" required maxlength="<?= MAX_NAME_LEN ?>" value="<?= e($name) ?>">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="email">邮箱(可选,不公开展示):</label>
|
||||||
|
<input type="email" id="email" name="email" maxlength="<?= MAX_EMAIL_LEN ?>" value="<?= e($email) ?>">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="content">留言内容 *(<?= MIN_CONTENT_LEN ?>-<?= MAX_CONTENT_LEN ?>字):</label>
|
||||||
|
<textarea id="content" name="content" rows="5" required maxlength="<?= MAX_CONTENT_LEN ?>"><?= e($content) ?></textarea>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn">提交留言</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="messages-section">
|
||||||
|
<h2>留言列表</h2>
|
||||||
|
<?php if (!$messages): ?>
|
||||||
|
<div class="no-messages">暂无留言,抢个沙发吧!</div>
|
||||||
|
<?php else: ?>
|
||||||
|
<?php foreach ($messages as $msg): ?>
|
||||||
|
<div class="message-card">
|
||||||
|
<div class="message-header">
|
||||||
|
<strong class="name"><?= e($msg['name']) ?></strong>
|
||||||
|
<span class="time"><?= e(date('Y-m-d H:i', strtotime((string)$msg['created_at']))) ?></span>
|
||||||
|
</div>
|
||||||
|
<div class="content"><?= nl2br(e($msg['content'])) ?></div>
|
||||||
|
<?php if (!empty($msg['reply'])): ?>
|
||||||
|
<div class="reply">
|
||||||
|
<strong>管理员回复:</strong>
|
||||||
|
<?= nl2br(e($msg['reply'])) ?>
|
||||||
|
<?php if (!empty($msg['replied_at'])): ?>
|
||||||
|
<span class="reply-time">(<?= e(date('Y-m-d H:i', strtotime((string)$msg['replied_at']))) ?>)</span>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<?php if ($total_pages > 1): ?>
|
||||||
|
<div class="pagination">
|
||||||
|
<span>第 <?= (int)$page ?>/<?= (int)$total_pages ?> 页</span>
|
||||||
|
<?php if ($page > 1): ?><a href="?page=<?= (int)$page - 1 ?>">上一页</a><?php endif; ?>
|
||||||
|
<?php if ($page < $total_pages): ?><a href="?page=<?= (int)$page + 1 ?>">下一页</a><?php endif; ?>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
<p>© <?= date('Y') ?> <?= e(SITE_NAME) ?></p>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
<script src="assets/script.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
88
login.php
Normal file
88
login.php
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* 管理员登录(加固版):CSRF + 登录限流 + 通用错误提示 + 登录后换 SID
|
||||||
|
*/
|
||||||
|
declare(strict_types=1);
|
||||||
|
require_once __DIR__ . '/config.php';
|
||||||
|
|
||||||
|
if (!empty($_SESSION['admin_logged_in'])) {
|
||||||
|
header('Location: admin.php');
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$error = '';
|
||||||
|
if (is_post()) {
|
||||||
|
require_csrf();
|
||||||
|
$username = get_post('username');
|
||||||
|
$password = get_post('password');
|
||||||
|
|
||||||
|
if ($username === '' || $password === '') {
|
||||||
|
$error = '请输入用户名和密码';
|
||||||
|
} elseif (!rate_limit('login:' . client_ip(), RATE_LIMIT_LOGIN, RATE_LIMIT_LOGIN_WINDOW)) {
|
||||||
|
$error = '尝试次数过多,请 10 分钟后再试';
|
||||||
|
log_error('登录限流触发 ip=' . client_ip());
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
$db = get_db();
|
||||||
|
$st = $db->prepare('SELECT id, password_hash FROM admins WHERE username = ?');
|
||||||
|
$st->bindValue(1, $username, SQLITE3_TEXT);
|
||||||
|
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);
|
||||||
|
if ($row && password_verify($password, (string)$row['password_hash'])) {
|
||||||
|
session_regenerate_id(true); // 防会话固定
|
||||||
|
$_SESSION['admin_logged_in'] = true;
|
||||||
|
$_SESSION['admin_username'] = $username;
|
||||||
|
$_SESSION['login_time'] = time();
|
||||||
|
header('Location: admin.php');
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
log_error('登录失败 username=' . $username . ' ip=' . client_ip());
|
||||||
|
$error = '用户名或密码错误';
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
log_error('登录异常: ' . $e->getMessage());
|
||||||
|
$error = '登录失败,请稍后再试';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>后台登录 - <?= e(SITE_NAME) ?></title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
<style>
|
||||||
|
body { background: #f5f5f5; }
|
||||||
|
.login-container { max-width: 400px; margin: 100px auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,.1); }
|
||||||
|
.login-form .form-group { margin-bottom: 15px; }
|
||||||
|
.login-form label { display: block; margin-bottom: 5px; font-weight: bold; }
|
||||||
|
.login-form input { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
|
||||||
|
.login-form button { width: 100%; padding: 10px; background: #2196f3; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
|
||||||
|
.login-form button:hover { background: #1976d2; }
|
||||||
|
.error { color: #f44336; margin-bottom: 15px; padding: 10px; background: #ffebee; border-radius: 4px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="login-container">
|
||||||
|
<h2 style="text-align:center;">后台登录</h2>
|
||||||
|
<?php if (!empty($_GET['timeout'])): ?>
|
||||||
|
<div class="error">登录已超时,请重新登录</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php if ($error !== ''): ?>
|
||||||
|
<div class="error"><?= e($error) ?></div>
|
||||||
|
<?php endif; ?>
|
||||||
|
<form method="POST" action="login.php" class="login-form">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="username">用户名:</label>
|
||||||
|
<input type="text" id="username" name="username" required autocomplete="username" value="<?= e(get_post('username')) ?>">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="password">密码:</label>
|
||||||
|
<input type="password" id="password" name="password" required autocomplete="current-password">
|
||||||
|
</div>
|
||||||
|
<button type="submit">登录</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
25
logout.php
Normal file
25
logout.php
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* 退出登录(POST + CSRF)
|
||||||
|
*/
|
||||||
|
declare(strict_types=1);
|
||||||
|
require_once __DIR__ . '/config.php';
|
||||||
|
|
||||||
|
if (is_post()) {
|
||||||
|
require_csrf();
|
||||||
|
}
|
||||||
|
$_SESSION = [];
|
||||||
|
if (ini_get('session.use_cookies')) {
|
||||||
|
$p = session_get_cookie_params();
|
||||||
|
setcookie(session_name(), '', [
|
||||||
|
'expires' => time() - 42000,
|
||||||
|
'path' => $p['path'],
|
||||||
|
'domain' => $p['domain'],
|
||||||
|
'secure' => $p['secure'],
|
||||||
|
'httponly' => $p['httponly'],
|
||||||
|
'samesite' => $p['samesite'] ?? 'Lax',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
session_destroy();
|
||||||
|
header('Location: login.php');
|
||||||
|
exit;
|
||||||
39
nginx.conf.example
Normal file
39
nginx.conf.example
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
# 留言系统 nginx 规则片段(贴到站点 server {} 里)
|
||||||
|
# 2026-10-30 · 配套 部署说明.md
|
||||||
|
# ⚠️ nginx 不读 .htaccess,这些规则必须显式配置
|
||||||
|
|
||||||
|
# 1) 数据库 / 日志 / 密钥 / 备份类文件一律封死
|
||||||
|
location ~* \.(db|sqlite|sqlite3|sql|log|ini|pem|key|p12|pfx|csr|bak|old|orig|swp|save)$ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2) 压缩包类(防止把源码/备份打包下载)
|
||||||
|
location ~* \.(tar|gz|tgz|zip|7z|rar|iso)$ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 3) 留言本的数据目录(若把数据放在 webroot 内)
|
||||||
|
location ^~ /guestbook/data/ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 4) 留言本里的敏感文件(初始密码、说明文档、sql)
|
||||||
|
location ~* ^/guestbook/([^\/]*\.(sql|md|txt)|initial-admin-password\.txt)$ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 5) 点文件(.env/.git/.user.ini 等)—— 站点通用规则,注意不能误伤 .well-known
|
||||||
|
location ~ /\.(?!well-known) {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 6) 防止上传目录执行脚本(若留言本后续加附件上传)
|
||||||
|
location ~* ^/guestbook/.*\.(php|phtml|php[3-8]|phar|cgi|pl|py|jsp|asp|aspx|sh|so)$ {
|
||||||
|
deny all;
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue