」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 PHP 中強制下載檔案?

如何在 PHP 中強制下載檔案?

發佈於2024-11-04
瀏覽:556

How to Force File Download in PHP?

在PHP 中強制下載文件

要在PHP 中提供文件的下載鏈接,您可以使用以下步驟:

  1. 檢索文件資訊:

    $filePath = '/path/to/file/on/disk.jpg';
    
    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);
    } else {
        die('The provided file path is not valid.');
    }
  2. 輸出標頭:

    header("Cache-Control: private");
    header("Content-Type: application/stream");
    header("Content-Length: ".$fileSize);
    header("Content-Disposition: attachment; filename=".$fileName);
  3. 輸出檔:

    readfile ($filePath);                   
    exit();

注意: 如果在函數中實現此功能以允許下載任意文件,請務必小心,因為您需要防止目錄遍歷並將下載限制為定義的區域。

版本聲明 本文轉載於:1729425315如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3