php Force下载不提示下载

时间:2013-09-13 08:33:28

标签: php header download

更新

刚从我的错误日志readfile() has been disabled for security reasons中找到了替代readfile()的替代方案? fopenfread会使用zip文件吗?

=============================================== ===================================

我的剧本:

<?php

$str = "some blah blah blah blah";
file_put_contents('abc.txt', $str); // file is being created
create_zip(array('abc.txt'), 'abc.zip'); // zip file is also being created

// now creating headers for downloading that zip

header("Content-Disposition: attachment; filename=abc.zip");
header("Content-type: application/octet-stream; charset=UTF-8");    
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
header('Content-Transfer-Encoding: binary'); // added this line as per suggestion
header('Content-Length: ' . filesize("abc.zip")); // added this line as per suggestion
readfile("abc.zip");
//echo 'do something'; // just for testing purpose to see if code is running till the end
exit;

当我运行上面的脚本时,我得到一个空白页面(没有下载提示)。当我取消注释“do something”行时,我会在屏幕上显示。所以脚本一直运行到最后一行。

我还将error_reporting(E_ALL)放在页面顶部,但没有显示任何内容。

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

尝试添加Content-Length标头。 有关完整示例,请参阅PHP readfile()文档。

答案 1 :(得分:0)

readfile()的一个替代方案是echo指向 ZIP 文件的链接,人们只需点击该文件即可,然后会提示您保存文件。

使用:echo "<a href='$filename'>File download</a>";

PHP

<?php
$str = 'some blah blah blah blah';
$zip = new ZipArchive();
$filename = "abc.zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE)==TRUE) {
$zip->addFromString("abc.txt", $str);
$zip->close();
}

echo "<a href='$filename'>File download</a>";
exit();
?>

这通常是ZIP文件的方式,然后打开提示save file as...

<?php
ob_start();
$str = 'some blah blah blah blah';

$zip = new ZipArchive();
$filename = "abc.zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
   exit("cannot open <$filename>\n");
}

$zip->addFromString("abc.txt", $str);
$zip->close();

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");

clearstatcache();
header("Content-Length: ".filesize('abc.zip'));

ob_flush();
readfile('abc.zip');
?>