”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 PHP 中强制下载文件?

如何在 PHP 中强制下载文件?

发布于2024-11-04
浏览:871

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