如何在 PHP 中下载文件

此教程将学习如何使用 PHP 下载文件。

只需按照以下示例轻松实现该目标。

使用 readfile() 函数

如果你想让不同类型的文件或者图片直接用PHP加载到用户的驱动器中,你可以运行readfile()函数。

让我们以创建图库为例,看看如何做到这一点,这用户一键下载图像文件。

在下面的示例中,生成了一个 image-gallery.php 并其中放置了一段代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Simple Image Gallery</title>
    <style>
      .img-box {
        display: inline-block;
        text-align: center;
        margin: 0 15px;
      }
    </style>
  </head>
  <body>
    <?php
    //Array encompassing sample image file names
    $images = array("kites.jpg", "balloons.jpg");

    //Looping through the array to generate an image gallery
    foreach($images as $image){
        echo '<div class="img-box">';
            echo '<img src="images/' . $image . '" width="200" alt="' .  pathinfo($image, PATHINFO_FILENAME) .'">';
            echo '<p><a href="download.php?file=' . urlencode($image) . '">Download</a></p>';
        echo '</div>';
    }
    ?>
  </body>
</html>

因此,在上面的示例中,下载链接指向 download.php 文件。
反过来,URL 包含图像文件名,就像查询字符串一样。
此外,我们还可以注意到, urlencode() 函数用于对图像文件名进行编码,使它们可以像 URL 参数一样安全地传递。
原因是文件名可能包含不安全的 URL 字符。
download.php,强制图片下载的完整代码如下:

<?php
if(isset($_REQUEST["file"])){
    //Get parameters
    $file = urldecode($_REQUEST["file"]); //Decode URL-encoded string
    /* Check if the file name includes illegal characters
    like "../" using the regular expression */
    if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
        $filepath = "images/" . $file;
        //Process download
        if(file_exists($filepath)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($filepath));
            flush(); //Flush system output buffer
            readfile($filepath);
            die();
        } else {
            http_response_code(404);
	        die();
        }
    } else {
        die("Invalid file name!");
    }
}
?>

其他文件格式,如pdf、doc等,也可以通过上面演示的方式下载。

重要的是要考虑在上面的示例中,正则表达式(第 8 行)不允许名称以点 (.) 开头或者结尾的文件。
例如,我们可以使用books.jpg 或者Books.jpg 等文件名,但不能使用books.jpg.、 .kites.jpg 等。

日期:2020-06-02 22:15:42 来源:oir作者:oir