【问题标题】:PHP readfile and download not workingPHP readfile和下载不起作用
【发布时间】:2018-04-16 18:53:19
【问题描述】:

我正在尝试编写一个可以在客户端下载文件的 PHP 脚本。该文件可以是 Excel (xlsx) 或 JSON。

The URL will look like:
http://<server>/php/download.php?file=/some/path/file.xlsx&name=file.xlsx&format=xlsx

我的 PHP 脚本如下所示:

<?php
if($_GET['format']==='excel') {
    header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
} else if($_GET['format']==='json') {
    header('Content-type: application/json');
}

header("Content-disposition: attachment; filename=".$_GET['name']);
readfile($_GET['file']);
?>

我已经仔细检查了实际文件没有损坏或任何东西。但是当我使用上面的 URL 时,会下载一个 0 大小的文件(尽管名称正确),显然这是错误的。我的 PHP 代码有什么问题?

【问题讨论】:

  • 请不要使用不安全的(用户)输入从您的服务器提供文件
  • URL 由我创建(我也在编写前端),它完全在我的控制之下。因此,传递给服务器的 GET 参数不是任意的,也不是由用户决定的。回到这个问题 - PHP 有什么问题无法提供文件?
  • 我的错!切换到error_reporting(E_ALL) 并注意到readfile() 已被管理员禁用。有没有其他方法可以在不使用readfile 的情况下提供文件供下载?
  • 检查变通方法并测试禁用的功能(这样您就知道可以选择哪些替代方案):stackoverflow.com/a/9289994/588079 GET 参数完全取决于用户,这不是开玩笑! 任何人都可以提出任何请求,从不相信用户输入!见owasp.org/index.php/Path_Traversal

标签: php content-type readfile


【解决方案1】:

我可以使用 echo file_get_contents($filename) 而不是服务器管理员禁用的 readfile 来做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 2022-07-04
    • 2012-08-04
    相关资源
    最近更新 更多