適用於任意檔案類型,支援斷點續傳(需額外處理 Range 請求)。
<?php
function downloadFile(string $filePath, string $fileName = ''): void
{
if (!is_file($filePath) || !is_readable($filePath)) {
http_response_code(404);
exit('檔案不存在或不可讀');
}
$fileName = $fileName ?: basename($filePath);
$fileSize = filesize($filePath);
$mime = mime_content_type($filePath) ?: 'application/octet-stream';
// 清除輸出緩衝
while (ob_get_level()) ob_end_clean();
header('Content-Description: File Transfer');
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $fileSize);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Expires: 0');
// 支援大檔案分塊輸出,避免記憶體耗盡
$handle = fopen($filePath, 'rb');
while (!feof($handle)) {
echo fread($handle, 8192);
flush();
}
fclose($handle);
exit;
}
?>
<?php
function simpleDownload(string $filePath): void
{
$info = pathinfo($filePath);
header('Content-Type: application/x-' . $info['extension']);
header('Content-Disposition: attachment; filename="' . $info['basename'] . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath); // 會將整個檔案讀入記憶體
exit;
}
?>
高併發、大檔案場景請使用 X-Sendfile / X-Accel-Redirect 讓 Web Server 直接發送檔案,PHP 僅負責權限驗證與頭部設置。