在 PHP 中强制下载文件

Muhammad Abubakar 2023年1月30日 2021年10月2日
  1. 在 PHP 中强制下载文件
  2. 使用 PHP 下载文件
  3. readfile() 函数
在 PHP 中强制下载文件

在本教程中,我们将学习如何在 PHP 中强制下载文件。

在 PHP 中强制下载文件

这个过程需要两个步骤:

  1. 创建用于处理要保护的文件的 PHP 文件。
  2. 在它出现的页面的 HTML 中添加一个相关的 PHP 文件。

将文件上传到服务器后,在文本编辑器中创建一个 PHP 文档。例如,如果你想强制下载 sample.pdf 而不是在线查看,请创建如下脚本。

<?php
header("Content-disposition: attachment; filename=sample.pdf");
header("Content-type: application/pdf");
readfile("sample.pdf");
?>

PHP 中的内容类型引用很重要:它是你要保护的文件的 MIME 类型。例如,如果你保存的是 MP3 文件,则需要用音频 MPEG 替换应用程序/pdf。

使用 PHP 下载文件

通常,你不需要使用 PHP 等服务器端脚本语言来下载图像、zip 文件、PDF 文档、exe 文件等。如果此类文件存储在可访问的公共文件夹中,你只需创建一个指向该文件的超链接,每次用户单击该链接时,浏览器都会自动下载该文件。

<a href="downloads/test.zip">Download Zip file</a>
<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download Image file</a>
<a href="downloads/setup.exe">Download EXE file</a>

readfile() 函数

你可以使用 PHP readfile() 函数强制将图像或其他文件类型直接下载到用户的硬盘驱动器。在这里,我们创建了一个简单的图片库,允许用户通过单击鼠标从浏览器下载图像文件。让我们创建一个名为 image-gallery.php 的文件并将以下代码放入其中。

 	<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Image Gallery</title>
<style type="text/css">
    .img-box{
        display: inline-block;
        text-align: center;
        margin: 0 15px;
    }
</style>
</head>
<body>
    <?php
    // Array containing sample image file names
    $images = array("hello.jpg", "resampled1.jpg");
    
    // Loop through array to create image gallery
    foreach($images as $image){
        echo '<div class="img-box">';
            echo '<img src="/examples/images/' . $image . '" width="200" alt="' .  pathinfo($image, PATHINFO_FILENAME) .'">';
            echo '<p><a href="/examples/php/download.php?file=' . urlencode($image) . '">Download</a></p>';
        echo '</div>';
    }
    ?>
</body>
</html>

如果你仔细查看上面的示例程序,你可以找到指向文件的下载链接; URL 还包括图像文件名作为查询字符串。我们还使用 PHP 的 urlencode() 函数对图像文件名进行编码,以便它们可以安全地作为 URL 参数传递,因为文件名可能包含不安全的 URL 字符。

这是"download.php"文件的完整代码,它强制下载图像。

<?php
if(!empty($_GET['file'])){
    $fileName = basename($_GET['file']);
    $filePath = 'files.txt/'.$fileName;
    if(!empty($fileName) && file_exists($filePath)){
        // Define headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$fileName");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        
        // Read the file
        readfile($filePath);
        exit;
    }else{
        echo 'The file does not exist.';
    }
}
    } else {
        die("Invalid file name!");
    }
}
?>

同样,你可以强制下载其他文件格式,如 Word Doc、PDF 文件等。上例中的正则表达式不允许名称以句点 . 开头或结尾的文件。例如,它允许像 hello.jpegresampled1.jpegmyscript.min.js 这样的文件名,但不允许 hello.jpeg..resampled.Jpeg.

相关文章 - PHP File