【问题标题】:Downloading a file using PHP saves an empty file使用 PHP 下载文件会保存一个空文件
【发布时间】:2022-11-19 13:34:44
【问题描述】:

我在我的 vps 服务器中创建了一个包含一些图像的 download.php 文件,如果用户使用此文件请求该文件,该文件将保存到设备中。但这会创建一个空文件。这是代码。

<?php
if(isset($_GET['file']))
{
    $filename = $_GET["file"];
    if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
        $filepath = "images/" . $file;
        if(file_exists($filepath)) {
            header("Content-Type: application/octet-stream");
            header("Content-Transfer-Encoding: Binary");
            header("Content-disposition: attachment; filename=\"".$filename."\""); 
           readfile($filepath);
        }
    }
?>

我已经更正了拼写错误并删除了 echo still ,它是一样的,当在服务器上调用 download.php?file=abstract.jpg 时下载文件。

【问题讨论】:

  • 打字错误,额外的下划线:readfile($filepath);
  • 你怎么服务这个?你如何调用它?这个问题实际上缺少minimal reproducible example,因此无法回答。我也看不到任何保存文件的地方。请作为这里的新用户,也带上tour并阅读How to Ask
  • 你不想echo readfile。它自己回声。
  • 另请注意,您不应该echo readfile(),只需readfile() 本身,因为它已经将文件转储到输出缓冲区。通过同时调用 echo,您将输出额外的信息,在本例中,是 readfile() 的返回值,即输出的字节数。

标签: php


【解决方案1】:

您的代码中仍然存在一些错误:

  1. 您的初始 if 块没有右括号

  2. 但是,核心问题实际上是您的 preg_match - 您正在向它传递一个尚未声明的变量 $file 。我想你的意思是传递 $filename。

    此代码有效:

    <?php
    if(isset($_GET['file']))
    {
        $filename = $_GET["file"];
        if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $filename)){
            $filepath = "images/" . $filename;
            if(file_exists($filepath)) {
                header("Content-Type: application/octet-stream");
                header("Content-Transfer-Encoding: Binary");
                header("Content-disposition: attachment; filename="".$filename."""); 
               readfile($filepath);
            }
        }
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 2021-01-07
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多