how can I have a file automatically download

Posted: 10:45 September 7, 2007
apache |

ok the title is possibley a little bit misleading … the other day a question on boards was how can I have a file automagically popup the save as dialogue when you click on it … other peoples responses were to add in some text saying right click on the file and choose save as … ridiculous but even I’ve done it in the past … distant past :D

My first solution was to write a php script and have that alter the headers of the file … the code is pretty simple

<?php
header(’Content-type: text/plain’);
header(’Content-Disposition: attachment;filename=”myfile.txt”‘);
readfile(’myfile.txt’);
?>

They weren’ too thrilled with that option and were wondering if there’s some way to do it with apache … to be honest I hadn’t a clue and I ended up doing a bit of research …

It would seem that adding in the following code

<filesmatch “\.(?i:txt)$”>
ForceType plain/txt
Header set Content-Disposition attachment
</filesmatch?>

will nicely alter the headers of the file without you having to go off writing and scripts … If you’ve any experience with regexp then you’ll see what the filesmatch piece is doing “\.(?i:txt)$” matching a . case insensitive txt match at the end ofthe filename

now you’ve two options you can include this code in your httpd.conf file or you could add it into you .htaccess file in the directory of choice. I think I’d prefer to add it to the directory as you’ve got greater control in future and don’t have to go mucking about with your main apache config file.

Please note that your apache server will have to have the headers_module up and running for this to work

Comments

Leave a Reply