Thursday, August 30, 2018

How do I Download a File to the User with my PHP script?

If you have a text file on your PHP server, you may have tried to download it through your PHP script with just this...

readfile("../data/MyTextFileName.txt");

But, as you would have noticed, it doesn't download the file. It displays the file contents in the browser.

To download the file, you must also include headers, used by HTTP to determine how to treat the web server's response, like this...

header("Content-disposition: attachment;filename=MyFileName.txt");
readfile("../data/MyTextFileName.txt");

After running the above, the user will be prompted with a question about whether they want to open or save a downloaded file, or however their particular browser is configured to handle downloads.

No comments:

Post a Comment