PHP创建文件下载,无需保存在服务器上 [英] PHP create file for download without saving on server

查看:127
本文介绍了PHP创建文件下载,无需保存在服务器上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.html)中有此文件:

So far: I have this in my html file (test.html):

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

这在我的test.php中:

and this in my 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并强制下载.

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?

推荐答案

发送标头后,只需echo,而不是将其保存到文件中即可.

Instead of saving it to a file, just echo it after you send the headers.

这篇关于PHP创建文件下载,无需保存在服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆