PHP: 综合项目:博客系统(下)

上一课搭好了博客骨架。这节课装修——编辑删除、评论互动、分页、安全加固,最后变成一个真正能上线展示的项目。

1. 文章编辑

(1) 给 Post 模型加方法

PHP
<?php
// app/Models/Post.php 追加方法

public function findByUser(int $id, int $userId): ?array
{
    $stmt = $this->db->prepare(
        "SELECT * FROM posts WHERE id = :id AND user_id = :userId"
    );
    $stmt->execute(['id' => $id, 'userId' => $userId]);
    $post = $stmt->fetch();
    return $post ?: null;
}

public function update(int $id, int $userId, string $title, string $content): bool
{
    $stmt = $this->db->prepare(
        "UPDATE posts SET title = :title, content = :content 
         WHERE id = :id AND user_id = :userId"
    );
    $stmt->execute([
        'id'      => $id,
        'userId'  => $userId,
        'title'   => $title,
        'content' => $content,
    ]);
    return $stmt->rowCount() > 0;
}

public function delete(int $id, int $userId): bool
{
    $stmt = $this->db->prepare(
        "DELETE FROM posts WHERE id = :id AND user_id = :userId"
    );
    $stmt->execute(['id' => $id, 'userId' => $userId]);
    return $stmt->rowCount() > 0;
}

public function getByUser(int $userId): array
{
    $stmt = $this->db->prepare(
        "SELECT * FROM posts WHERE user_id = :userId ORDER BY created_at DESC"
    );
    $stmt->execute(['userId' => $userId]);
    return $stmt->fetchAll();
}

(2) 控制器对应方法

PHP
<?php
// 追加到 PostController

/** 编辑表单 */
public function editForm(array $params): string
{
    $this->requireLogin();
    $post = $this->post->findByUser((int)$params['id'], $_SESSION['user']['id']);
    if (!$post) {
        http_response_code(404);
        return '<h2>文章不存在或你无权编辑</h2>';
    }
    ob_start();
    require __DIR__ . '/../../views/posts/edit.php';
    return ob_get_clean();
}

/** 处理编辑 */
public function edit(array $params): string
{
    $this->requireLogin();
    $userId = $_SESSION['user']['id'];
    $id = (int)$params['id'];

    $title   = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');

    if ($title === '' || $content === '') {
        return '<p style="color:red">标题和内容不能为空</p><a href="javascript:history.back()">返回</a>';
    }

    $success = $this->post->update($id, $userId, $title, $content);
    if (!$success) {
        return '<p style="color:red">文章不存在或你无权编辑</p>';
    }

    header("Location: /posts/{$id}");
    exit;
}

/** 删除文章 */
public function delete(array $params): void
{
    $this->requireLogin();
    $userId = $_SESSION['user']['id'];
    $id = (int)$params['id'];

    $this->post->delete($id, $userId);
    header("Location: /posts/my");
    exit;
}

/** 我的文章 */
public function myPosts(): string
{
    $this->requireLogin();
    $posts = $this->post->getByUser($_SESSION['user']['id']);
    ob_start();
    require __DIR__ . '/../../views/posts/my.php';
    return ob_get_clean();
}

2. 评论功能

(1) 创建评论表

▶ 示例:评论功能实现

SQL
CREATE TABLE comments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    post_id INT NOT NULL,
    user_id INT NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
▶ 试一试

(2) 评论模型

PHP
<?php
// app/Models/Comment.php
namespace App\Models;

use App\Core\Database;
use PDO;

class Comment
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function getByPost(int $postId): array
    {
        $stmt = $this->db->prepare(
            "SELECT c.*, u.username 
             FROM comments c 
             JOIN users u ON c.user_id = u.id 
             WHERE c.post_id = :postId 
             ORDER BY c.created_at ASC"
        );
        $stmt->execute(['postId' => $postId]);
        return $stmt->fetchAll();
    }

    public function create(int $postId, int $userId, string $content): int
    {
        $stmt = $this->db->prepare(
            "INSERT INTO comments (post_id, user_id, content) 
             VALUES (:post_id, :user_id, :content)"
        );
        $stmt->execute([
            'post_id' => $postId,
            'user_id' => $userId,
            'content' => $content,
        ]);
        return (int)$this->db->lastInsertId();
    }
}

(3) 文章详情页——带评论视图

PHP
<?php
// views/posts/show.php(改进版)
$commentModel = new \App\Models\Comment();
$comments = $commentModel->getByPost($post['id']);

$title = $post['title']; 
ob_start();
?>

<article>
    <h2><?= htmlspecialchars($post['title']) ?></h2>
    <div class="post-meta">
        作者:<?= htmlspecialchars($post['username']) ?> | 
        <?= $post['created_at'] ?>
    </div>
    <div style="line-height:1.8;margin:20px 0">
        <?= nl2br(htmlspecialchars($post['content'])) ?>
    </div>
    
    <?php if (isset($_SESSION['user']) && $_SESSION['user']['id'] === (int)$post['user_id']): ?>
        <p>
            <a href="/posts/<?= $post['id'] ?>/edit">编辑</a> | 
            <a href="/posts/<?= $post['id'] ?>/delete" onclick="return confirm('确认删除?')">删除</a>
        </p>
    <?php endif; ?>
</article>

<!-- 评论列表 -->
<h3>评论(<?= count($comments) ?>)</h3>
<?php foreach ($comments as $c): ?>
    <div style="border-bottom:1px solid #eee;padding:10px 0">
        <strong><?= htmlspecialchars($c['username']) ?></strong>
        <span style="color:#999;font-size:12px">
            <?= date('Y-m-d H:i', strtotime($c['created_at'])) ?>
        </span>
        <p><?= nl2br(htmlspecialchars($c['content'])) ?></p>
    </div>
<?php endforeach; ?>

<!-- 发表评论 -->
<?php if (isset($_SESSION['user'])): ?>
    <h4>发表评论</h4>
    <form method="POST" action="/posts/<?= $post['id'] ?>/comment">
        <textarea name="content" rows="3" required placeholder="写下你的评论..."></textarea>
        <button type="submit" style="margin-top:8px">发表</button>
    </form>
<?php else: ?>
    <p><a href="/login">登录</a>后即可评论</p>
<?php endif; ?>

<p style="margin-top:20px"><a href="/posts">← 返回文章列表</a></p>

<?php $content = ob_get_clean(); require __DIR__ . '/../layout.php'; ?>

3. 分页

PHP
<?php
// Post 模型:分页查询
public function getPaginated(int $page = 1, int $perPage = 10): array
{
    $offset = ($page - 1) * $perPage;
    
    $stmt = $this->db->prepare(
        "SELECT p.*, u.username 
         FROM posts p 
         JOIN users u ON p.user_id = u.id 
         WHERE p.status = 'published' 
         ORDER BY p.created_at DESC 
         LIMIT :limit OFFSET :offset"
    );
    // PDO 的 LIMIT/OFFSET 必须用 bindValue + 类型
    $stmt->bindValue(':limit', $perPage, \PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, \PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll();
}

public function count(): int
{
    return (int)$this->db->query(
        "SELECT COUNT(*) FROM posts WHERE status = 'published'"
    )->fetchColumn();
}

▶ 示例:分页组件

PHP
<?php
// 分页 HTML 组件
function renderPagination(int $currentPage, int $totalPages, string $baseUrl): string
{
    if ($totalPages <= 1) return '';
    
    $html = '<div style="display:flex;gap:8px;margin-top:20px">';
    
    for ($i = 1; $i <= $totalPages; $i++) {
        $active = $i === $currentPage ? 'background:#4a90d9;color:white' : '';
        $html .= "<a href='{$baseUrl}?page={$i}' 
                  style='padding:6px 12px;border:1px solid #ddd;border-radius:4px;
                  text-decoration:none;{$active}'>{$i}</a>";
    }
    
    $html .= '</div>';
    return $html;
}
▶ 试一试

4. 安全加固清单

PHP
// 安全加固汇总

// 1. 所有输出都 htmlspecialchars
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// 2. 所有数据库操作用预处理
$stmt = $pdo->prepare("UPDATE posts SET title = :t WHERE id = :id AND user_id = :uid");
$stmt->execute(['t' => $title, 'id' => $id, 'uid' => $_SESSION['user']['id']]);

// 3. 敏感操作验证权限(不仅是显示按钮,后端必须验证)
public function delete(array $params): void
{
    $this->requireLogin();
    // ✅ 验证当前用户是文章作者
    $this->post->delete((int)$params['id'], $_SESSION['user']['id']);
}

// 4. Session 安全配置
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_secure', '1');   // HTTPS 时打开
ini_set('session.cookie_samesite', 'Lax');

// 5. 密码哈希永不用明文
$hash = password_hash($password, PASSWORD_DEFAULT);

// 6. CSRF Token(简要版)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_POST['_token'] !== $_SESSION['_token']) {
        die('CSRF 攻击已阻止');
    }
}
// 在表单中:<input type="hidden" name="_token" value="<?= $_SESSION['_token'] ?>">

5. 部署检查清单

TEXT 📖 仅展示
部署前检查:
□ display_errors = Off(生产环境)
□ error_log 路径可写
□ 数据库密码不是 root/空
□ session.cookie_secure = 1(如果 HTTPS)
□ 上传目录权限正确(不允许执行 PHP)
□ .env 文件不被 web 访问(放 web 目录外)
□ SSL 证书已配置(Let's Encrypt 免费)
□ robots.txt 和 sitemap.xml 已生成

❓ 常见问题

Q 博客系统功能越来越多,代码开始乱了怎么办?
A 这正是框架(Laravel/Symfony)解决的问题。你现在理解了 Router、Controller、Model、View 这些概念,下一课学 Laravel 时你会发现"这不就是把我手写的这些用更优雅的方式实现了吗"。
Q 评论怎么防垃圾?
A 方案递进:(1) 必须登录才能评论(最简单);(2) 加验证码 reCAPTCHA(免费);(3) 内容审核(敏感词过滤 + 人工审核);(4) 频率限制(同一用户 60 秒内不能重复评论)。

❓ 常见问题

Q 这个概念和 XXX 有什么区别?
A 简洁对比两者的核心差异和使用场景。

📖 小节

📝 作业

  1. 给博客系统添加"编辑文章"和"删除文章"功能(仅作者可操作)。
  2. 实现评论功能:文章详情页显示评论列表 + 登录用户可发表评论。
  3. 给文章列表加分页(每页显示 5 篇),首页、文章列表页都支持分页。
Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏