2014-07-25 297 views
0

我需要创建一个自动启动下载文件的PHP页面(我不想公开下载链接)。我已经在网上尝试了几个例子,但所有的例子最终都会以不正确的内容类型在浏览器中打开文件。 例如:无法用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'); 
?> 

当我执行这个页面,浏览器的输出是: enter image description here 尝试这个例子中的所有可能的变型后,我的想法是,这个问题是我的托管环境。我应该检查哪个变量,并可能要求启用我的提供程序?
谢谢!

+0

尝试添加更多'header()'。 'header(“Content-Transfer-Encoding:Binary”);'和'header(“Content-Length:”.filesize($ file));' –

+0

哇,我一直在使用PHP很长一段时间,从来没有听说过'readfile()'函数。我一直使用'fopen('php:// output','w')'来完成下载。 :)你有没有尝试过使用无缓存头文件? “Pragma:no-cache”,“Expires:0”也许? – Cypher

+0

你正在使用哪个Web服务器? – Cypher

回答

1

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

+0

感谢猜测!用gzip内容类型它的工作! – user2824073

+0

准确地说,这是正确的更改应用:标题(“内容类型:应用程序/ gzip”); – user2824073

0

下面是我在当天使用的代码:

     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的内容类型标题即可。

+0

工作与“gzip”内容。谢谢无论如何。 – user2824073