萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 文章系統:刪除文章同步清理靜態 HTML 快取檔案

業務邏輯

採用靜態化架構時,文章發布生成 .html,刪除文章時必須同步刪除對應靜態檔,避免殘留垃圾檔案佔用磁碟、造成 404/舊內容被搜尋引擎收錄。

完整刪除流程

<?php
// del_article.php
require_once __DIR__ . '/../inc/conn.php'; // PDO 連線

$id = (int)($_GET['id'] ?? 0);
$path = $_GET['path'] ?? ''; // 相對靜態目錄的路徑,如 'news/2024/123.html'

if (!$id || !$path) {
    die('參數缺失');
}

// 1. 刪除資料庫記錄 (使用預處理防注入)
$stmt = $pdo->prepare("DELETE FROM news_content WHERE news_id = ?");
$stmt->execute([$id]);

// 2. 刪除靜態檔案
$staticRoot = __DIR__ . '/../newslist'; // 靜態檔根目錄
$fullPath = $staticRoot . '/' . $path;

// 安全檢查:防止目錄遍歷攻擊
$realStaticRoot = realpath($staticRoot);
$realFullPath = realpath($fullPath);
if ($realFullPath && str_starts_with($realFullPath, $realStaticRoot)) {
    if (file_exists($realFullPath)) {
        unlink($realFullPath);
        echo "已刪除靜態檔: $path\n";
    }

    // 3. 可選:清理空目錄 (避免大量空資料夾)
    $dir = dirname($realFullPath);
    while ($dir !== $realStaticRoot && $dir !== false) {
        if (count(scandir($dir)) === 2) { // 只有 . 和 ..
            rmdir($dir);
            $dir = dirname($dir);
        } else {
            break;
        }
    }
} else {
    error_log("非法路徑嘗試: $path");
}

// 4. 重導向回列表
header('Location: list.php');
exit;
?>

關鍵安全細節

  • 路徑穿透防護:必須用 realpath() 解析並確認在允許根目錄下。
  • 權限控制:確認當前用戶有權刪除該文章 (RBAC/所有權檢查)。
  • 軟刪除優先:生產系統建議 deleted_at 軟刪除,定期批次清理靜態檔。

擴充:更新文章時重新生成

function regenerate_static(int $articleId, string $template): void {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM news_content WHERE news_id = ?");
    $stmt->execute([$articleId]);
    $article = $stmt->fetch();
    if (!$article) return;

    // 渲染模板 (可用 Twig/Blade/原生 PHP)
    ob_start();
    include $template; // 內部使用 $article 變數
    $html = ob_get_clean();

    $staticPath = "/newslist/{$article['category']}/{$articleId}.html";
    $fullPath = __DIR__ . '/..' . $staticPath;
    $dir = dirname($fullPath);
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    file_put_contents($fullPath, $html);

    // 更新資料庫靜態路徑
    $pdo->prepare("UPDATE news_content SET static_path = ? WHERE news_id = ?")
        ->execute([$staticPath, $articleId]);
}

架構建議

  • 靜態檔儲存於 Web 根目錄外,由 Nginx X-Accel-Redirect 或 PHP 讀取輸出,避免直接 URL 存取繞過權限。
  • 使用 雲端儲存 (S3/OSS) + CDN 替代本地檔案,支援多機房、自動備份。
  • 引入 快取失效機制:發布/更新/刪除 → 發送事件 → Worker 非同步重建/刪除靜態檔。
copyright © 萬盛學電腦網 all rights reserved