Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a text file for download on-the-fly

Update #1

What has been posted below is spot on for getting it to output the file. What it is doing though is outputting the string data followed by the rest of the forms HTML. Is there any way to stop what is put into the file and what is just displayed to the browser.

Update #2

Just added exit() and all works fine. Thanks!

EOU

Hi,

I've been looking around and seen a few things similar but not quite fully got the grasp on what I need to do to achieve the task fully.

At the moment I have a form that a user supplies some details. On submit it is posted back to itself and the POST variables processed. I have a premade HTML web template for the information to be placed into which works fine and dandy just doing a str_replace.

What I am trying to do now is export that as a download to the user in a plain text document. So the end result being the user clicks submit on the form and they then have a download popup open with the modified webpage as a .txt file.

As far as I understand I need to do something using HTTPs headers functionality. What exactly though to achieve what I want I'm not sure. I only want the file to be available once, but I assume it has to be stored somewhere initally for the user to download which will then need cleaing up after manually?

Any help or points would be great! Thanks.

like image 226
lethalMango Avatar asked Dec 06 '10 22:12

lethalMango


People also ask

How do you create a text file example?

Another way to create a text file is to right-click an empty area on the desktop, and in the pop-up menu, select New, and then select Text Document. Creating a text file this way opens your default text editor with a blank text file on your desktop. You can change the name of the file to anything you want.


1 Answers

No need to store it anywhere. Just output the content with the appropriate content type.

<?php     header('Content-type: text/plain'); ?>Hello, world. 

Add content-disposition if you wish to trigger a download prompt.

header('Content-Disposition: attachment; filename="default-filename.txt"'); 
like image 95
Quentin Avatar answered Oct 18 '22 13:10

Quentin