-1

I am looking for a way that the results from a search generates a file that can be downloaded and saves by the user into their computer. I am already able to generate the file, however, it gets stored on the server automatically rather than prompting the user where to store it.

In the search form the user can select a checkbox to generate a CSV file of the output (I would prefer to just have a download button on the results page but was unable to figure out how to do that): https://www.evernote.com/shard/s68/sh/54e95567-d91e-4649-a5c1-35b5f8929c13/a4bc4fed2a2c7f7801099f6d5711c49e

Then in the next page the results are shown on the page and the appropriate file is also generated.

Code that generates the file on the results page:

if($print_flag == 1) {
  $filename = "exportfile" . date("Y-m-d_H_m_s") . ".csv";
  $handle = fopen($filename, 'w+');
  fputcsv($handle, array($column1,$column2));
  fclose($handle);
}

$print_flag is set if the user checks the CSV checkbox in the prior form.

This creates a file that is stored on the server rather than allowing the user to save it locally.

I saw this previous questions PHP save file to users computer but could not figure out how to add those headers or whether that was the right approach.

Thanks!

Community
  • 1
  • 1
Danconia
  • 543
  • 2
  • 12
  • 28
  • Following the advice of @hexafraction, I ended up doing this: http://stackoverflow.com/questions/12094080/download-files-from-server-php – Danconia Aug 12 '13 at 22:21

1 Answers1

0

Most browsers use mime-type headers for this reason.

Generally, any calls to set headers should be as early as possible. It is imperative that they go before any echo statements, and there is nothing outside a <?php ?> block that goes before them.

You will need to put two lines into the code, again as early as possible:

header('Content-type: text/csv');

This tells the browser that this is a csv file, and sets the types of files filtered for in the browser's save-as dialog.

header("Content-disposition: attachment;filename=$name.csv");

tells the browser to offer to save the file. Depending on the browser, it can either pop up a full save as dialog, or more commonly, save a file to the default downloads folder called $name.csv. The double-quotes allow the filename to be included simply by setting $name.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • thanks for your answer. But the code that generates my file is withing larger code base. Would I set these headers just for the output file? – Danconia Aug 12 '13 at 17:41
  • @LuisP Yes, only set these for the actual request that gets the file. – nanofarad Aug 12 '13 at 18:56