定時將動態頁面 (PHP/JSP/ASP) 渲染結果抓取並存為靜態 HTML,部署至 CDN 或靜態空間,大幅降低伺服器負載並提升首屏速度。
<?php
/**
* generate_static.php
* 從來源 URL 抓取內容,寫入暫存檔,原子性替換目標靜態檔
*/
$srcUrl = 'https://localhost/index.php'; // 來源動態頁面
$targetFile = 'index.html'; // 目標靜態檔
$tempFile = 'temp_' . basename($targetFile); // 暫存檔 (避免併發衝突)
echo "<h1>生成靜態頁面: {$targetFile}</h1>\n";
// 1. 清理舊暫存檔
@unlink($tempFile);
// 2. 開啟遠端 URL 串流 (需 php.ini allow_url_fopen=On)
$fp = @fopen($srcUrl, 'rb');
if (!$fp) {
die("<p style='color:red'>無法開啟來源 URL: {$srcUrl}</p>");
}
// 3. 讀取內容 (限制 10MB 防止異常佔用記憶體)
$content = stream_get_contents($fp, 10 * 1024 * 1024);
fclose($fp);
if ($content === false || $content === '') {
die("<p style='color:red'>讀取內容為空或失敗</p>");
}
// 4. 寫入暫存檔
$tf = @fopen($tempFile, 'wb');
if (!$tf) {
die("<p style='color:red'>無法建立暫存檔</p>");
}
fwrite($tf, $content);
fclose($tf);
// 5. 原子性替換 (rename 在同一檔案系統上為原子操作)
if (!@rename($tempFile, $targetFile)) {
// 跨裝置 fallback
@copy($tempFile, $targetFile);
@unlink($tempFile);
}
echo "<p style='color:green'>靜態頁面更新成功!</p>";
echo "<p>大小: " . number_format(strlen($content) / 1024, 2) . " KB</p>";
echo "<p>時間: " . date('Y-m-d H:i:s') . "</p>";
php.ini 必須啟用,否則 fopen() 無法開啟 HTTP 串流。若不可用,改用 cURL。'rb'/'wb' 確保 Windows 上不轉換換行符,保持內容位元組完整。fread 更簡潔,可限制最大讀取長度防止惡意大檔。rename() 在同一檔案系統上為原子操作,避免讀取者看到半寫入檔案;跨裝置退回 copy+unlink。$ch = curl_init($srcUrl);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_USERAGENT => 'StaticGenerator/1.0',
CURLOPT_SSL_VERIFYPEER => true,
]);
$content = curl_exec($ch);
if (curl_errno($ch)) {
die('cURL 錯誤: ' . curl_error($ch));
}
curl_close($ch);
0 * * * * /usr/bin/php /path/generate_static.php >/dev/null 2>&1 (每小時)。「動態生成、靜態服務」是經典高效能架構模式。上述腳本提供最小可行性實作,生產環境請加入日誌記錄、監控告警、併發鎖、內容雜湊比對 (未變更則跳過) 等健壯性機制。