Force download vs display in bowser.

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Force download vs display in bowser.

Post by hawleyjr »

I have a text file that is used to import data into a 3rd party application. There is a link to this text file on my site.

Code: Select all

<a href="update.txt">Here</a>
The problem I'm having is when the user clicks the link the text file is opened in the browser. I would like for the user to be prompted to download the file not view it in their browser.

Some options I have considered are the following but all have their issues.
  • Save txt file in a zip file and have the user download the zip file.
    Change the file type to something the browser won't try to read.
I'm not too particular about saving to a zip file because I don't want to add more steps for my user then are necessary.

Changing the file type will up my help desk calls when users are unable to open the file on their desktop. For instance, if I named the file *.txt2 the users computer will not know what application to view the file with.

Any ideas or suggestions?
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

To 'force' a download prompt you can do:

$filename = 'whateveryouwant.txt';
header ('Content-type: text/plain');
header ('Content-Disposition: attachment; filename='.$filename);
readfile('update.txt');

So you could put the above code in say, download.php, and use <a href="download.php">download</a> for example.
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

Thanks, it works great.

I only made the following modification:

Code: Select all

$filename = 'test.txt'; 
header ('Content-type: text/plain'); 
header ('Content-Disposition: attachment; filename='.$filename); 
readfile($filename);
Post Reply