在一种"一步一步"/"向导"的设置中,我尝试向用户发送一个新创建的纯文本文件。
问题列表:在本地主机(windows, xampp)上,它按预期工作,但在远程机器(托管的web空间)上执行时,它在浏览器窗口中以纯文本形式提供文件内容。(在同一浏览器下测试:chrome)
文件是一个纯文本文件,里面有一个数据库备份(只有几个条目,不大),在下载前一步创建。下一步是删除它,这也很好。文件本身有效,所有句柄已关闭。浏览器中显示的内容是包含所有行的实际文件。
$_POST在下载工作时进行消毒,为了简化,未消毒的atm:
<?php
require_once('CSettings.php');
$s = new CSettings();
$file = $_POST['file'];
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Length: ' . filesize($file));
readfile($file);
}
?>
<form action="index.php" method="post" accept-charset="UTF-8">
<input type="submit" value="Delete backup file from the server" class="btn_red">
<input type="hidden" value="<?php echo $file; ?>" name="file">
<input type="hidden" value="delete_backup" name="view">
</form>
有什么建议吗?摆弄内容类型已经无济于事了。最后的办法是压缩整个文件,然后再试一次,但这会使它变得不必要的复杂。
一个可能有效的解决方案是使用download html属性,但是,它似乎不支持Safari。
点击链接时下载文件(而不是导航到文件):
<a href="/images/myw3schoolsimage.jpg" download>
从:http://www.w3schools.com/tags/att_a_download.asp
但是,这可能需要您将下载放在单独的脚本中。你也可以看看这里:如何在PHP中自动启动下载?