Force Download HTML and TXT Files in PHP – PHP Tutorial

By | July 31, 2019

When you are using your browser to open a html or txt file, they will be opened by our broweser and not downloaded into your computer. In this tutorial, we will introduce you how to download them, not open them by using php.

php download file

Create a html or txt file

$filename = 'somefile.txt';

Set http response header

header("Content-Type: text/html");
/* Tell the browser how big the file is going to be */
header("Content-Length: ".filesize($filename)."\n\n");
/* force the file to be downloaded */
header("Content-Disposition: attachment; filename=$filename");

Notify user to download

echo file_get_contents($filename)

Then when you open a txt file by browser, it will ask you to download this file or not.

Category: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *