Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP创建文件,然后强制用户下载-不起作用_Php_Forms_Post - Fatal编程技术网

PHP创建文件,然后强制用户下载-不起作用

PHP创建文件,然后强制用户下载-不起作用,php,forms,post,Php,Forms,Post,因此,我有一个用户填写的表单,它们被发送到一个php页面,该页面通过$u POST发送所有变量,然后将输出写入一个txt文件那很好用。我的问题是,我试图强迫用户在创建文件的同一页面上下载它,在创建文件后,我似乎无法让它工作,除了创建的文件之外,什么也没有发生 以下是我所拥有的基本知识: 编辑:发现问题-我的fclose线路出现致命错误。。。你知道怎么了吗 $myfile="c-form" . date('m-d-Y_hia').'.txt'; $fileHandle = fopen($myfil

因此,我有一个用户填写的表单,它们被发送到一个php页面,该页面通过$u POST发送所有变量,然后将输出写入一个txt文件那很好用。我的问题是,我试图强迫用户在创建文件的同一页面上下载它,在创建文件后,我似乎无法让它工作,除了创建的文件之外,什么也没有发生

以下是我所拥有的基本知识:

编辑:发现问题-我的fclose线路出现致命错误。。。你知道怎么了吗

$myfile="c-form" . date('m-d-Y_hia').'.txt';
$fileHandle = fopen($myfile, 'w');
//write stuff to file
$fclose($fileHandle);
//file is now closed
//now force user to download file that was just made
header('Content-disposition: attachment; filename=$myfile');
header('Content-type: text/plain');

试着这样做:

$myfilename="c-form".date('m-d-Y_hia').'.txt';
// collect the data to the be returned to the user, no need to save to disk
// unless you really want to, if so, use file_put_contents()
$dataForFile="test data to be returned to user in a file";

header('Content-type: application/x-download');
header('Content-Disposition: attachment; filename="'.$myfilename.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.strlen($dataForFile));
set_time_limit(0);
echo $dataForFile;
exit;

无需使用
fopen()
fclose()
file\u get\u contents()
file\u put\u contents()
将为您完成所有这些,并且已经完成多年。

您需要在下面的行中使用双引号:

header("Content-disposition: attachment; filename=$myfile");

好的,那么在您的代码中,您实际上在哪里将文件内容作为POST响应的一部分发送回来?为什么要将内容写入文件,而不是仅在标题后输出它?
附件;filename=…
实际上不会自己传输。你是说在用户提交表单并将内容写入文件之后,还是在文件关闭并应下载之后?@mario那么我该如何传输文件呢?你的第一句话有些混乱。数据是从您的服务器发布还是发布到您的服务器?有关我以前从未使用过的文件\u put\u contents()或文件\u get\u contents()的更多信息,我将如何实现这些内容以替代fopen和fclose?我仍然需要将其保存到磁盘。@John-的PHP文档和比我在这里做的工作要好得多。我阅读了文件内容,它对我有效,因为我在fclose上遇到了一个致命错误,所以我将标记您的解决方案作为答案。