PHP 可透過串流封裝協定直接讀取遠端資源,本文示範如何抓取網路檔案並安全儲存為本地靜態頁面,包含錯誤處理與臨時檔案機制。
fopen() 開啟遠端串流(需啟用 allow_url_fopen)<?php
// 設定參數
$srcUrl = 'https://example.com/page.php';
$tempFile = 'temp_page.html';
$targetFile = 'page.html';
// 清理舊臨時檔
@unlink($tempFile);
// 開啟遠端串流
$handle = @fopen($srcUrl, 'r');
if (!$handle) {
die('無法連線至遠端來源: ' . $srcUrl);
}
// 讀取內容(限制 1MB 防異常)
$content = '';
while (!feof($handle)) {
$content .= fread($handle, 8192);
if (strlen($content) > 1024 * 1024) {
fclose($handle);
die('內容超過大小限制');
}
}
fclose($handle);
// 寫入臨時檔
$tempHandle = fopen($tempFile, 'w');
if (!$tempHandle) {
die('無法建立臨時檔案');
}
fwrite($tempHandle, $content);
fclose($tempHandle);
// 原子性替換:先複製再刪除
if (copy($tempFile, $targetFile)) {
unlink($tempFile);
echo '靜態頁面更新成功!';
} else {
die('檔案替換失敗');
}
?>
Last-Modified / ETag 避免重複下載mb_convert_encoding()抓取外部資源存在 XSS、惡意腳本注入風險,儲存前務必進行內容過濾或僅作靜態封存,勿直接輸出至前端。