首页  >  文章  >  后端开发  >  如何使用 PHP 标头和文件处理强制文件下载?

如何使用 PHP 标头和文件处理强制文件下载?

Linda Hamilton
Linda Hamilton原创
2024-10-20 20:00:30591浏览

How to Force File Downloads Using PHP Headers and File Handling?

在 PHP 中强制下载文件

允许用户从您的网站下载图像或其他文件是一项常见要求。在 PHP 中,可以通过利用适当的标头和文件处理技术来实现此任务。

标头操作

要强制下载文件,我们必须将适当的标头发送到浏览器。这些标头控制浏览器行为并指示其下载文件而不是在浏览器窗口中显示文件。一些重要的标头包括:

<code class="php">header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);  // File size in bytes
header("Content-Disposition: attachment; filename=".$fileName);  // File name to display</code>

文件输出

正确设置标头后,我们需要输出文件本身。这是使用 PHP readfile() 函数完成的,该函数读取文件数据并将其发送到浏览器。

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

代码示例

将它们放在一起,这是一个在 PHP 中强制下载图像的示例脚本:

<code class="php"><?php
    // Fetch the file info.
    $filePath = '/path/to/file/on/disk.jpg';

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

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

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
?></code>

创建下载面板

如果您不想立即下载文件,而是更喜欢面板要显示以供用户确认,您可以稍微修改脚本。这是一个示例:

<code class="html"><a href="download.php?file=/path/to/file.jpg">Download</a></code>

在 download.php 中,您可以显示一个确认面板,其中包含一个触发实际文件下载的按钮:

<code class="php"><?php
    $file = $_GET['file'];

    if(file_exists($file)) {
        // Display confirmation panel...
        if(isset($_POST['confirm'])) {  // Confirm button clicked
            header("Cache-Control: private");
            header("Content-Type: application/stream");
            header("Content-Length: ".filesize($file));
            header("Content-Disposition: attachment; filename=".basename($file));

            readfile ($file);                   
            exit();
        }
    }
    else {
        die('Invalid file path.');
    }
?></code>

此方法允许您提供用户拥有更人性化的下载机制。

以上是如何使用 PHP 标头和文件处理强制文件下载?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn