繁体   English   中英

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

[英]PHP create file, then force user to download it - not working

因此,我有一个用户完成的表单,它们被发送到php页面,该页面通过$ _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');

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

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

尝试这样的事情:

$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_get_contents()file_put_contents()会为您完成所有工作,并且已经完成了很多年。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM