首頁  >  文章  >  後端開發  >  如何在 PHP 中強制下載檔案?

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

DDD
DDD原創
2024-10-20 19:57:02508瀏覽

How to Force File Download in PHP?

在PHP 中強制下載文件

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

  1. 檢索文件信息:

    <code class="php">$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.');
    }</code>
  2. 輸出標頭:

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

    <code class="php">readfile ($filePath);                   
    exit();</code>

注意:在函數中實現此操作時要允許此運算下載任意文件,因為您需要防止目錄遍歷並將下載限製到定義的區域。

以上是如何在 PHP 中強制下載檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn