【问题标题】:PHP forced download jpg -- viewer saying file is corruptPHP 强制下载 jpg - 查看器说文件已损坏
【发布时间】:2014-03-16 23:17:02
【问题描述】:

我只是玩了一会儿,我正在使用 php 强制将文件从我的数据库下载到 ole'desktop,下载部分很好,然后当我打开文件时(如果在查看器中它是jpg)应用程序告诉我文件已损坏

这是html

<form action="view_file.php" method="post" name="downloadform">
      <input name="file_name" type="hidden" value=<?php echo $row['file_path'];?>>
      <input name="file_type" type="hidden" value=<?php echo $row['file_type'];?>>
      <button type="submit" value="Secure Download" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 btn btn-default pull-left view_file"><span class="glyphicon glyphicon-cloud-download"></span> Secure Download</button>
</form>

这是我的 php sn-p //清理输出缓冲区 ob_clean();

//If statement gets everything started
if(isset($_POST['file_name'])){

     //Grab global variables from the HTML form
     $file = $_POST['file_name'];
     $file_type2 = $_POST['file_type'];

     //Grab last item in array then explode to only grab the file name
     $filename = array_pop(explode('/', $file));

          //Grab file type from global variables in HTML form
          header("Content-type: ".$file_type2."");

          ////Grab file path from global variables in HTML form
          header('Content-Disposition: attachment; filename="'.$filename.'"');
          readfile($file);
               exit();
}

有什么建议吗??

【问题讨论】:

  • 用文本编辑器打开文件,检查顶部是否有php错误或html
  • 我发现的错误是 Strict Standards: Only variables should be passed by reference in
  • 你应该检查请求的是什么文件,否则可以下载任何文件。

标签: php http-headers


【解决方案1】:

我认为您的问题可能是您尝试读取文件名不完整的文件。试试

$fullfilename = $filename.'.'.$file_type2;
readfile($fullfilename);

然后看看会发生什么。另外,就像其他人所说...用文本编辑器打开文件并阅读错误。您可能需要打开错误报告。你用

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

【讨论】:

    【解决方案2】:

    正如错误消息“只能通过引用传递变量”所说,您正在为使用通过引用传递的参数的函数提供常量值。

    我认为问题出在这里:

    $filename = array_pop(explode('/', $file));
    

    array_pop 第一个参数通过引用传递,因为在此过程中数组被修改。你应该使用一个临时变量:

    $filepathArray = explode('/', $file);
    $filename = array_pop($filepathArray);
    

    或者更好的是,使用最适合您想要做的事情的 basename 函数:

    $filename = basename($file);
    

    【讨论】:

    • 嘿卢卡斯,我遇到的问题是,即使我使用 basename 它告诉我 $filename 变量是空的,在我的数据库中我保存了完整路径,basename() 给了我该路径的末尾,但我认为它无法访问该文件,因为路径已经消失,你知道吗?
    • 警告:readfile(test.odt):打开流失败:第 9 行的 C:\xampp\htdocs\casekeeper_directory\view_file.php 中没有这样的文件或目录
    【解决方案3】:

    我想我遇到了类似的问题。

    这是因为 readfile() 有一个 4096 字节的缓冲区。

    这意味着当您的页面通过单击提交重新加载时

    在您的 readfile() 进入此缓冲区之前写入的任何内容,在开始下载之前。

    但是这个“随便”大于 4096 字节,超出的部分会被要下载的文件卡住,从而损坏它。

    尝试将 snpiset 放在 view_file.php 的开头,而不是放在末尾。

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多