【问题标题】:file corrupt when click download link单击下载链接时文件损坏
【发布时间】:2011-10-01 16:38:06
【问题描述】:

我尝试使用php强制下载图片jpg文件,我实现了eth下面的代码:

html

<a href = "filedownload.php?src=uploads/myimage.jpg&download=true>download this file</a>

下载.php

 <?php
ob_start();
 include_once 'functions.php';

if (isset($_GET['download']) && $_GET['download'] == 'true')
  {    

  $src = sanitizeString($_GET['src']);
  header('Content-Description: File Transfer');   
  header('Content-Type: image/jpeg');  
  header('Content-Disposition: attachment; filename='.basename($src));  
  header('Content-Transfer-Encoding: binary');  
  header('Expires: 0');   
  header('Cache-Control: public');  
  header('Pragma: public');

  } 

 ?>

假设图片的完整路径是“www.example.com/smith/topic/uploads/myimage.jpg”,我得到了正确的图片名称并且也出现了下载窗口,但图片已损坏并且大小为 1KB,任何人都可以告诉我为什么,非常感谢。

【问题讨论】:

  • 文件里面有什么?我敢打赌,啤酒里面有一条 PHP 错误消息,解释了出了什么问题。
  • 哪个代码?这就是我为那部分所拥有的一切
  • 一方面,PHP 脚本的开头有一个空格,这是一个禁忌。您还忘记了在您的 href 末尾添加“”。您甚至在其中打印文件内容吗?PS:我强烈建议您处理这样的文件。潜在攻击的地方太多了。
  • @smith 好吧,您实际上是在哪里输出文件的数据?
  • 试试 yo var_dump(basename($src)) 并检查这是否是图像的填充路径?!

标签: php html


【解决方案1】:

这里是如何使用 readfile 函数的示例

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

【讨论】:

    【解决方案2】:

    您需要一些实际通过文件发送的代码。参见例如readfilefpassthru

    【讨论】:

    • @smith 将它放在最后一个大括号之前。你可能还想检查文件是否真的在目录中,以防攻击者使用你的脚本读取它之外的东西(例如/../../../../etc/passwd
    • 你的意思是把它放在basename($file)之后吗?
    • header('Pragma: public');之后
    • 所以通过文件发送的代码在您提供的链接中?
    • @smith 两个链接都包含有关如何将文件作为附件发送的示例(在描述或 cmets 中)。
    【解决方案3】:

    尝试使用:

    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    

    【讨论】:

      猜你喜欢
      • 2013-02-13
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 2017-12-04
      • 2019-01-28
      • 1970-01-01
      相关资源
      最近更新 更多