採用靜態化架構時,文章發布生成 .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() 解析並確認在允許根目錄下。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]);
}
X-Accel-Redirect 或 PHP 讀取輸出,避免直接 URL 存取繞過權限。