萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP header() 函數實現文件下載完整指南

PHP header() 函數核心用法解析

在 PHP 開發中,header() 函數不僅能發送原始 HTTP 報頭,更是實現文件下載功能的關鍵工具。本文將系統梳理其核心應用場景,並提供可直接落地的代碼範例。

一、HTTP 狀態碼與跳轉控制

header() 最常見的用途是頁面跳轉與狀態碼輸出:

1. 頁面重定向

<?php
// 多次調用以最後一次為準(需無輸出內容)
header('Location: https://www.example.com');
exit(); // 最佳實踐:跳轉後立即終止腳本
?>

注意:若跳轉前有 echo 輸出,第二個 header 將生效(如輸出後跳轉至 Google)。

2. 權限控制與錯誤頁面

<?php
// 401 未授權
header('HTTP/1.1 401 Unauthorized');
header('Status: 401 Unauthorized');

// 404 頁面不存在(偽裝頁面不存在)
header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found');
?>

二、文件下載核心實現

通過設置 Content-Type 與 Content-Disposition 實現強制下載:

基礎下載範例(PDF 文件)

<?php
$filename = '/path/to/real_file.pdf'; // 服務器絕對路徑
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="download_name.pdf"');
readfile($filename);
exit();
?>

通用二進制流下載(適用於任意文件)

<?php
$file = 'server_file.rar';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="download_name.rar"');
readfile($file);
exit();
?>

三、常用 MIME 類型對照表

正確的 MIME 類型能提升瀏覽器識別準確性:

副檔名MIME 類型
.pdfapplication/pdf
.docapplication/msword
.docxapplication/vnd.openxmlformats-officedocument.wordprocessingml.document
.xlsapplication/vnd.ms-excel
.xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.zipapplication/x-zip-compressed
.rarapplication/octet-stream
.jpg/.jpegimage/jpeg
.pngimage/png
.mp3audio/mpeg
.mp4video/mp4
.txttext/plain
.htmltext/html
.jstext/javascript
.csstext/css

四、進階技巧與避坑指南

  • 大文件下載:建議搭配 fread() 分塊讀取,避免記憶體溢出
  • 中文檔名:需進行 URL 編碼 urlencode($filename) 或使用 RFC 5987 格式
  • 緩存控制:添加 header('Cache-Control: no-cache, must-revalidate') 防止緩存干擾
  • 輸出緩衝:下載前調用 ob_clean() 清除前序輸出,確保文件純淨

五、完整生產級下載函數封裝

<?php
function downloadFile($filePath, $downloadName = '', $mimeType = '') {
    if (!is_file($filePath)) {
        header('HTTP/1.1 404 Not Found');
        exit('文件不存在');
    }
    
    $downloadName ?: $downloadName = basename($filePath);
    $mimeType ?: $mimeType = mime_content_type($filePath) ?: 'application/octet-stream';
    
    // 清除輸出緩衝
    if (ob_get_level()) ob_clean();
    
    header('Content-Type: ' . $mimeType);
    header('Content-Disposition: attachment; filename="' . rawurlencode($downloadName) . '"');
    header('Content-Length: ' . filesize($filePath));
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: no-cache');
    
    readfile($filePath);
    exit();
}
?>
copyright © 萬盛學電腦網 all rights reserved