【问题标题】:Unable to force download file with PHP无法使用 PHP 强制下载文件
【发布时间】:2014-07-25 16:07:10
【问题描述】:

我需要创建一个 PHP 页面,它会自动开始下载文件(我不想公开下载链接)。我在网上尝试了几个示例,但所有示例最终都会在浏览器中以不正确的内容类型打开文件。 例如:

 <?php
// We'll be outputting a ZIP
header("Content-type: application/zip");

// Use Content-Disposition to force a save dialog.
// The file will be called "downloaded.zip"
header("Content-Disposition: attachment; filename=downloaded.zip");

readfile('downloaded.zip');
?>

当我执行这个页面时,浏览器上的输出是: 在尝试了此示例的所有可能变体之后,我的想法是问题出在我的托管环境上。我应该检查哪个变量,并可能要求对我的提供者启用?
谢谢!

【问题讨论】:

  • 尝试添加更多header()s。 header("Content-Transfer-Encoding: Binary");header("Content-Length: ".filesize($file));
  • 哇,我已经使用 PHP 很长时间了,从来没有听说过 readfile() 函数。我一直使用fopen('php://output', 'w') 来完成下载。 :) 您是否尝试过使用无缓存标头? "Pragma: no-cache", "Expires: 0" 也许?
  • 您使用的是哪个网络服务器?
  • 您还可以探索符号链接来隐藏文件的实际链接。
  • 尝试了所有,不幸的是没有成功:-(

标签: php


【解决方案1】:

尝试使用 phpinfo() 打印出以下变量:SERVER["HTTP_ACCEPT_ENCODING"]。 我的怀疑是你没有 zip 允许 - 例如可能是不同的东西,比如“gzip”。

【讨论】:

  • 确切地说,这是要应用的正确更改:header("Content-type: application/gzip");
【解决方案2】:

这是我以前使用的代码:

                        header ("Content-Type: application");
                        header ("Content-Disposition: attachment; filename=\"$file\"");
                        header ("Content-Length: " . filesize ('./FILES/' . $file));
                        header ("Cache-Control: no-cache");
                        header ("Pragma: no-cache");
                        readfile ('./FILES/' . $file);
只需修改c的content-type header即可。

【讨论】:

    猜你喜欢
    • 2013-12-07
    • 2010-11-03
    • 2010-11-30
    • 1970-01-01
    • 2012-01-19
    • 2011-11-08
    • 2012-11-11
    相关资源
    最近更新 更多