PHP 创建文件以供下载,而无需保存在服务器上
2022-08-30 14:54:06
最终目标:我想创建一个网页,用户可以在其中输入表单中的信息。有了这些信息,我想通过将给定的信息插入到模板中来创建一个html文件(下面称为test-download.html),然后强制下载。由于我想在即将到来的研讨会上演示这一点,人们将在“同时”使用它,因此我不想将文件保存在服务器上,而只是强制下载。
迄今:我在我的html文件中有这个(测试.html):
<form action="test.php" method="post">
To file: <input type="text" name="tofile" />
<input type="submit" />
</form>
在我的测试中.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);
?>
这将覆盖文件测试下载.html文件并强制下载。
问题:如何在不弄乱服务器上的文件(测试下载.html)的情况下执行此操作?