PHP创建文件供下载而不保存在服务器上


PHP create file for download without saving on server

最终目标:我想创建一个网页,用户可以在表单中输入信息。有了这些信息,我想创建一个html文件(下面称为test-download.html),方法是将给出的信息插入到模板中,然后强制下载。因为我想在即将到来的研讨会上演示这一点,人们将在"同一时间"使用它,所以我不想将文件保存在服务器上,而只是强制下载。

到目前为止:我在我的html文件(test.html):

<form action="test.php" method="post">
To file: <input type="text" name="tofile" />
<input type="submit" />
</form>

在test.php中:

<?php
$filename = 'test-download.html';
$htmlcode1 = "<HTML> 'n <BODY>";
$htmlcode2 = "</BODY> 'n <HTML>";
$somecontent = $htmlcode1.$_POST["tofile"].$htmlcode2;
!$handle = fopen($filename, 'w');
fwrite($handle, $somecontent);
fclose($handle);

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; "); 
header("Content-Transfer-Encoding: binary");
readfile($filename);
?>

这将覆盖文件test-download.html文件并强制下载。

问题:如何在不搞乱服务器上的文件(test-download.html)的情况下做到这一点?

不要将其保存到文件中,只需在发送标题后将其echo

要知道,几乎每次PHP脚本响应请求时,它都会"生成一个文件"并被浏览器下载。任何echo, print, printf,或以其他方式输出到标准输出的内容都是该"文件"的内容。

你所要做的就是告诉浏览器应该以不同的方式处理"文件"——你输出的头应该已经这样做了。发送报头后,打印出的任何内容都将成为下载的内容。