I want the users of my php script to be able to download the contents of a certain text file from my server but I don't want them to download it directly from my server so I want to go through a php file called download.php
I use this code to trigger the file prompt
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=textfile.txt");
header("Content-Length: " . filesize('textfile.txt');
$fp = fopen('textfile.txt', "r");
fpassthru($fp);
fclose($fp);
The code works, the file gets downloaded but it seems the code ignores new lines of that text file.
Let's say the content of the original text file is
word1 word2 word3 word4 word5
The content of the downloaded file would be
word1word2word3word4word5
How can I fix it that the downloaded file actually retains the new lines of the original text file?
Here's a code to convert text file EOLs from Linux, Windows and Mac to Windows. So no matter what EOLs your file has it will open fine on Win.
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=textfile.txt");
header("Content-Length: " . filesize('textfile.txt'));
$f = file_get_contents('textfile.txt');
$f = str_replace("\r\n", "\n", $f); //Convert Windows to Unix
$f = str_replace("\r", "\n", $f); //Convert Mac to Unix
$f = str_replace("\n", "\r\n", $f); //Convert Unix to Windows
echo $f;
The code is short but it's not too good for huge files.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.