萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

PHP 定時產生靜態首頁:output buffering 控制與檔案時間戳判斷

應用場景

虛擬主機無法設定排程任務 (cron),需在使用者造訪時自動判斷是否重新產生靜態首頁,平衡效能與即時性。

核心函數:Output Buffering 控制

函數用途
ob_start()開啟輸出緩衝區,後續 echo/HTML 暫存於記憶體
ob_get_contents()取得緩衝區內容為字串
ob_end_clean()關閉緩衝區並清空 (若用 ob_end_flush() 則輸出至瀏覽器)

完整實作流程

<?php
// 1. 檢查靜態檔是否存在且未過期 (10分鐘 = 600秒)
if (file_exists("./index.htm")) {
    $now = time();
    if ($now - filemtime("./index.htm") < 600) {
        header("Location: ./index.htm");
        exit;
    }
}

// 2. 開啟緩衝區,執行動態邏輯
ob_start();
?>
<html><head><title>動態首頁</title></head><body>
<h1>歡迎來到動態首頁</h1>
<p>現在時間:<?= date('Y-m-d H:i:s') ?></p>
<?php include "latest_news.php"; ?>
</body></html>
<?php
// 3. 取得緩衝內容並寫入靜態檔
$content = ob_get_contents();
ob_end_clean();

$fp = fopen("./index.htm", 'w');
fwrite($fp, $content) or die('寫入失敗');
fclose($fp);

// 4. 導向靜態檔 (或直接 echo $content)
header("Location: ./index.htm");
?>

關鍵細節

  • filemtime() 取得檔案最後修改時間 (Unix timestamp)
  • 時間差判斷邏輯:$now - filemtime(...) < $interval
  • 寫入模式 'w' 會覆蓋舊檔,確保內容最新
  • 最後 header("Location: ...") 導向靜態檔,後續請求直接由 Web Server 靜態服務,零 PHP 開銷

進階擴充

  • 多頁面靜態化:封裝為函數 generateStatic($template, $output, $ttl)
  • 快取失效策略:後台更新資料時 unlink() 強制刪除靜態檔
  • 壓縮輸出:ob_start('ob_gzhandler') 開啟 gzip
  • CDN 整合:靜態檔部署至 CDN,配合 Purge API
copyright © 萬盛學電腦網 all rights reserved