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