為了避免 PHP readfile() 函數導致的緩存問題,您可以使用以下方法:
文件系統緩存控制:
通過設置 HTTP 響應頭中的 Cache-Control 和 Expires 字段,您可以控制瀏覽器和代理服務器如何緩存文件。例如,您可以將文件設置為不緩存:
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Expires: 0');
這將確保瀏覽器不會緩存 readfile() 讀取的文件。
文件內容的時間戳:
您可以在輸出的 HTML 中添加一個時間戳參數,以確保瀏覽器總是請求文件的最新版本。例如:
$file = 'path/to/your/file.html';
$mtime = filemtime($file);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Expires: 0');
readfile($file);
這將告訴瀏覽器在文件內容發生更改時請求新版本。
使用 readfile() 的替代方法:
如果您需要更多的控制,可以考慮使用 file_get_contents() 函數代替 readfile()。file_get_contents() 函數提供了更多的選項,例如設置超時和錯誤處理。此外,它不會受到 PHP 設置中的默認 max_execution_time 和 memory_limit 的限制。例如:
$file = 'path/to/your/file.html';
$content = file_get_contents($file);
echo $content;
通過使用這些方法,您可以避免 PHP readfile() 函數導致的緩存問題。