<?php
$filepath = '/path/to/file.zip';
$filename = basename($filepath);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit();
?>
適用任意檔案類型,強制瀏覽器彈出「另存新檔」對話框。
<?php
$filename = '/path/to/document.pdf';
$fileinfo = pathinfo($filename);
header('Content-Type: application/x-' . $fileinfo['extension']);
header('Content-Disposition: attachment; filename="' . $fileinfo['basename'] . '"');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit();
?>
簡潔但依賴副檔名判斷 MIME,不準確時瀏覽器可能直接開啟而非下載。
function downloadLargeFile($path, $chunkSize = 1024 * 1024) { // 1MB
$handle = fopen($path, 'rb');
if (!$handle) { http_response_code(404); exit; }
while (!feof($handle)) {
echo fread($handle, $chunkSize);
@ob_flush(); @flush();
}
fclose($handle);
}
realpath() 正規化,確保在允許目錄內Content-Security-Policy、X-Content-Type-Options: nosniff