<?php
function downloadFile(string $fileurl, int $forceDownload = 1): void {
// 1. 遠端檔案:直接 302 導向
if (strpos($fileurl, ':/') !== false) {
header("Location: $fileurl");
exit;
}
// 2. 本地檔案處理
if ($forceDownload === 0) {
// 直接導向站內 URL
header("Location: " . SITE_URL . $fileurl);
exit;
}
// 強制下載模式
// 解析實體路徑 (防止目錄遍歷)
$realPath = file_exists($fileurl) ? $fileurl : PHPCMS_ROOT . $fileurl;
$realPath = realpath($realPath);
// 安全檢查:必須在允許目錄內
$allowedBase = realpath(PHPCMS_ROOT . 'upload/');
if ($realPath === false || strpos($realPath, $allowedBase) !== 0) {
header('HTTP/1.1 403 Forbidden');
exit('非法檔案路徑');
}
if (!is_file($realPath) || !is_readable($realPath)) {
header('HTTP/1.1 404 Not Found');
exit('檔案不存在或不可讀');
}
$filename = basename($realPath);
// 3. 中文檔名編碼處理 (RFC 5987 / RFC 6266)
if (preg_match('/[\x80-\xFF]/', $filename)) {
// 現代瀏覽器支援 UTF-8 編碼檔名
$encodedName = rawurlencode($filename);
header("Content-Disposition: attachment; filename*=UTF-8''{$encodedName}");
// 兼容舊瀏覽器 (IE) 提供 fallback
header("Content-Disposition: attachment; filename=\"{$encodedName}\"");
} else {
header("Content-Disposition: attachment; filename=\"{$filename}\"");
}
// 4. 輸出檔案
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($realPath));
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes'); // 支援斷點續傳
header('Cache-Control: private, must-revalidate');
header('Pragma: private');
header('Expires: 0');
readfile($realPath); // 直接輸出,不佔用 PHP 記憶體
exit;
}
?>
realpath() 解析真實路徑 + strpos($real, $base) === 0 確保在允許目錄樹下。filename*=UTF-8''... (RFC 5987) 為主,舊式 filename="..." 為備援。readfile() 而非 file_get_contents() + echo,避免記憶體爆炸;配合 Accept-Ranges 支援續傳。finfo_file() 偵測真實 MIME 類型,而非統一 octet-stream。將檔案讀取交給 Web Server,PHP 僅驗權並發送 Header:
<?php
// Nginx 配置需在 location 設定 internal 路徑
header('X-Accel-Redirect: /protected-files/' . $relativePath);
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($filename));
header('Content-Type: application/octet-stream');
exit;
?>
優點:PHP 進程立即釋放、支援 sendfile 系統呼叫、高併發下載不阻塞 PHP-FPM。