1

I have a file, index2.php that has been written to by a form.

The whole content of this file, I have stored within a variable $final_code using an output buffer.

I now wish to add a "Download" button to the end of the page, that brings up a Save As dialog, allowing the user to save this file's source code (i.e. the variable) as a .txt - But I'm stumped.

index2.php:

<?php

// Start buffering the output
ob_start();

?>

<!-- INDEX2.PHP HTML ELEMENTS HERE -->

<?php
// Store the contents of the buffer
$final_code = ob_get_contents();

// Print the contents of the buffer
ob_end_flush();
?>

<form action="savefile.php" method="post">

Happy? Save this to file: <input type="submit" name="savefile" value="Save" />

</form>

I'm not sure if this needs to be worked in to this file or savefile.php, so the latter is currently blank.

mpdc
  • 3,550
  • 5
  • 25
  • 48
  • see [this SO question](http://stackoverflow.com/questions/4458119/display-save-as-dialog-and-save-contents-of-a-selected-text-inside-textarea-to) – jaudette Dec 12 '12 at 12:03

3 Answers3

5

i think you cannot force a save as file dialog in browser.

for forceing the download of a txt file i do the following:

header('Pragma: anytextexeptno-cache', true);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"example.txt\"");
echo $output;

hope that helps.

steven
  • 4,868
  • 2
  • 28
  • 58
1

You need to use headers to force download:

 $file = 'somefile.zip';

 if(!file)
 {
     // File doesn't exist, output error
     die('file not found');
 }
 else
 {
     // Set headers
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Disposition: attachment; filename=$file");
     header("Content-Type: application/zip");
     header("Content-Transfer-Encoding: binary");

     // Read the file from disk
     readfile($file);
 }

Example taken from: http://www.ryboe.com/tutorials/php-headers-force-download

See link for further explanation.

Mitch Satchwell
  • 4,770
  • 2
  • 24
  • 31
  • How does one get the contents of my variable `$final_code` within this file? Thank you. – mpdc Dec 12 '12 at 12:17
  • This gives me an "The Compressed (zipped) Folder is invalid or corrupted." error - and it also runs on **index2.php** page load, not on button click... – mpdc Dec 12 '12 at 12:38
  • Should I move all of this code to **savefile.php** via a hidden form input, and post the $final_code variable there before working on it? – mpdc Dec 12 '12 at 12:39
  • If it is a text file you are trying to save you will need to change the filename ($file) and content-type to match this. Content-type should be `text/plain`. – Mitch Satchwell Dec 12 '12 at 12:42
0

Are you looking for PHP Download Script(from browser) ?

Vaibhav
  • 289
  • 1
  • 3
  • 11