javascript - PHP create file out of POST, then force user to download it - not working

234

I have a page with some forms and input fields, which the user fills in and then they are sent to a php page via Ajax and $_POST. And then the php File 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 the code where the .txt File is created (this works nice):

$myfile = fopen("test.txt", "w") or die("Unable to open file!");

foreach ($URLsArray as &$url) {
     $row=$SomeArray[$keys[$index]]."\t".$SomeArray[$keys[$index]]."\t".$SomeArray[$keys[$index]]."\t".$SomeArray[$keys[$index]]."\t".$url."\n";
     fwrite($myfile, $zeile);
     $index = $index  + 1;
}
fclose($myfile);

And here the code, where I try to force the download: (after the fclose)

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('test.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('test.txt'));
readfile('test.txt');
exit;

And when I try this I get the error: "Unexpected token A". "A" is the first letter in the test.txt, which is created.

And I know that there are a lot of similar questions, but not one solution worked for me.

I hope someone can help me :)

726

Answer

Solution:

Instead of doing this backend with PHP you could try to do this on the frontend part. The easiest solution is to write some JavaScript code which adds an iframe to your webpage. The iframe should then have a href to the file you want the user to download.

353

Answer

Solution:

Okay here my solution: @CBroe thanks for the hint with the background request, I would have tried for ages to get the download work in the php file. So what I did:

In PHP: I echo the filename after the .txt file is created:

echo json_encode(array('filename' => "your_Data".time().".txt"));

Than in JavaScript I read the filename in the success method and put the link in an<a> element. Later that will be a button which is set active.

success : function(data) {
        $("#button_get_file_download").attr("href", "urlToFolder"+data.filename);
},

People are also looking for solutions to the problem: php - How to authenticate with Sentinel by username?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.