tags:

views:

35

answers:

3

Hey,

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 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

A: 

As far as i know notepad removes those line endings in this case.

Thariama
A: 

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"]);
Col. Shrapnel
Fair point but we don't know if the original file has a unix or Windows formatting
Steve Claridge
Thank you for your concerns. I've only posted a snippet; I'll worry about security when I have the script working how I need it to.
Rich
A: 

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

Victor Nicollet
Sorry, I was messing with the code! It was set as binary.
Rich