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

DDD
發布: 2024-10-20 19:57:02
原創
508 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!