I want to 'force' the download of a plain text file in PHP.
I have the following code, which I picked up on the web somewhere:
if (isset($_REQUEST["file"])) {
$file=$_REQUEST["file"];
header("Content-type: application/force-download");
header("Content-Transfer-Encoding: ansi");
header("Content-length: ".filesize($file));
header("Content-disposition: attachment; filename=".basename($file));
echo @fileread("$file");
}
else
{
echo "No file selected";
}
This seems to work fine, however when the开发者_JAVA技巧 file is opened in Windows with notepad, the line endings are not preserved. Could anyone offer a solution to this (text files must be created with notepad)?
Thanks, Rich
As far as i know notepad removes those line endings in this case.
readfile()
, not fileread. and yes' it's not readfile, PHP or even web-server issue. it's just unix and windows plain text format difference.
in unix it's \n
while in windows it's \r\n
you have to create these files using windows format
also note that your code is highly insecure. and let an attacker to read any file you have, including passwords etc. at least make it
$file=basename($_REQUEST["file"]);
To the best of my knowledge, ansi
is not a valid content transfer encoding. Since you want to preserve the contents of the file as-is (and those contents may contain long lines and CRLF line endings), you probably want to use binary
精彩评论