So I have a form that users complete, and they are sent to a php page that sends all the variables via $_POST and then writes the output to a txt file. - that works just fine. My problem is I am trying to force the user to download it on that same page that creates the file, after the file is created and I can't seem to get it to work, nothing happens besides the file being created....
Here are the basics of what i have:
EDIT: Found the problem - I am getting a fatal error on the line with my fclose... any ideas what's wrong there?
$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");
Try something like this:
$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;
There is no need to use fopen()
and fclose()
, file_get_contents()
and file_put_contents()
will do all that for you, and has done for years now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.