php 强制下载不提示下载


php Force Download not Prompting for Download

Update

刚刚从我的错误日志中发现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;

当我运行上面的脚本时,我得到一个空白页(没有下载提示)。当我取消注释"做某事"行时,我会在屏幕上看到它。因此,脚本一直运行到最后一行。

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

我在这里错过了什么?

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

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();
?>

这通常是压缩文件然后打开提示以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');
?>