<?php
$file = 'images/test.jpg';
$filename = 'testname.jpg';
if (!file_exists($file)) { http_response_code(404); exit('檔案不存在'); }
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('Content-Length: ' . filesize($file));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($file);
exit;
| Header | 用途 |
|---|---|
Content-Type: application/octet-stream | 強制瀏覽器下載而非開啟 |
Content-Disposition: attachment; filename="..." | 指定下載檔名,rawurlencode 處理中文 |
Content-Length | 顯示進度條、支援斷點續傳基礎 |
Cache-Control / Pragma | 避免代理快取干擾 |
function sendFile($path, $name = null) {
if (!file_exists($path)) { http_response_code(404); return; }
$name = $name ?? basename($path);
$size = filesize($path);
$mime = mime_content_type($path) ?: 'application/octet-stream';
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . rawurlencode($name) . '"');
header('Accept-Ranges: bytes');
header('Content-Length: ' . $size);
// 處理 Range 請求
if (isset($_SERVER['HTTP_RANGE'])) {
$range = $_SERVER['HTTP_RANGE'];
if (preg_match('/bytes=(\d+)-(\d*)/', $range, $m)) {
$start = (int)$m[1];
$end = $m[2] ? (int)$m[2] : $size - 1;
if ($start >= $size || $end >= $size) {
header('HTTP/1.1 416 Range Not Satisfiable');
header('Content-Range: bytes */' . $size);
return;
}
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
header('Content-Length: ' . ($end - $start + 1));
$fp = fopen($path, 'rb');
fseek($fp, $start);
while (!feof($fp) && ($pos = ftell($fp)) <= $end) {
$chunk = min(8192, $end - $pos + 1);
echo fread($fp, $chunk);
@ob_flush(); @flush();
}
fclose($fp);
return;
}
}
// 完整檔案輸出
$fp = fopen($path, 'rb');
while (!feof($fp)) {
echo fread($fp, 8192);
@ob_flush(); @flush();
}
fclose($fp);
}
HTTP 回應只能有一個 Content-Disposition,無法單一請求推送多檔。
<!-- 方案一:隱藏 iframe -->
<iframe src="download.php?file=1.zip" style="display:none"></iframe>
<iframe src="download.php?file=2.zip" style="display:none"></iframe>
<!-- 方案二:JS 依序觸發 -->
<script>
['1.zip', '2.zip', '3.zip'].forEach(f => {
var a = document.createElement('a');
a.href = 'download.php?file=' + encodeURIComponent(f);
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
</script>
$file = realpath($baseDir . '/' . $input); if (strpos($file, $baseDir) !== 0) die('非法路徑');finfo_file 或 mime_content_type,勿信任副檔名。readfile 內部已分塊,但手動 fread 更可控),禁用 file_get_contents 載入整檔。sleep() 或 Nginx limit_rate。