PHP 创建下载文件而不保存在服务器上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5560373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP create file for download without saving on server
提问by Thomas
Ultimate goal:I want to create a webpage where a user can enter information in forms. With that information I want to create a html file (below called test-download.html) by inserting the information given into a template and then force a download. Since I want to demonstrate this at an upcoming workshop where people will be using this at the "same time" I would like to not save the file on the server and just force the download.
最终目标:我想创建一个用户可以在表单中输入信息的网页。有了这些信息,我想通过将给定的信息插入模板来创建一个 html 文件(以下称为 test-download.html),然后强制下载。由于我想在即将举行的研讨会上演示这一点,人们将在“同时”使用它,因此我不想将文件保存在服务器上,而只是强制下载。
So far:I have this in my html file (test.html):
到目前为止:我的 html 文件(test.html)中有这个:
<form action="test.php" method="post">
To file: <input type="text" name="tofile" />
<input type="submit" />
</form>
and this in my test.php:
这在我的 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);
?>
This overwrites the file test-download.html file and forces a download.
这会覆盖文件 test-download.html 文件并强制下载。
Question:How can I do this without messing with a file (the test-download.html) on the server?
问题:如何在不弄乱服务器上的文件(test-download.html)的情况下执行此操作?
回答by alex
Instead of saving it to a file, just echoit after you send the headers.
不是将其保存到文件中,echo而是在发送标头后保存。
回答by cHao
Realize that nearly every time a PHP script responds to a request, it's "generating a file" that's downloaded by the browser. Anything you echo, print, printf, or otherwise put out to standard output is the contents of that "file".
意识到几乎每次 PHP 脚本响应请求时,它都会“生成一个文件”,并由浏览器下载。您echo、print、printf或以其他方式输出到标准输出的任何内容都是该“文件”的内容。
All you have to do is tell the browser that the "file" should be handled differently -- and the headers you're outputting should already do that. Once the headers are sent, anything you print out becomes contents of the download.
你所要做的就是告诉浏览器“文件”应该以不同的方式处理——你输出的标题应该已经这样做了。发送标头后,您打印的任何内容都将成为下载内容。

