title: PHP create file for download without saving on server
body: <p><strong>Ultimate goal:</strong> I want to create a webpage where a user can enter information in forms. With that information I want to create a html file (below called test-download.html) by inserting the information given into a template and then force a download. Since I want to demonstrate this at an upcoming workshop where people will be using this at the "same time" I would like to not save the file on the server and just force the download.</p>
  
  <p><strong>So far:</strong> I have this in my html file (test.html):</p>
  
  <pre><code>&lt;form action="test.php" method="post"&gt;
  To file: &lt;input type="text" name="tofile" /&gt;
  &lt;input type="submit" /&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>and this in my test.php:</p>
  
  <pre><code>&lt;?php
  $filename = 'test-download.html';
  $htmlcode1 = "&lt;HTML&gt; \n &lt;BODY&gt;";
  $htmlcode2 = "&lt;/BODY&gt; \n &lt;HTML&gt;";
  $somecontent = $htmlcode1.$_POST["tofile"].$htmlcode2;
  !$handle = fopen($filename, 'w');
  fwrite($handle, $somecontent);
  fclose($handle);
  
  
  header("Cache-Control: public");
  header("Content-Description: File Transfer");
  header("Content-Length: ". filesize("$filename").";");
  header("Content-Disposition: attachment; filename=$filename");
  header("Content-Type: application/octet-stream; "); 
  header("Content-Transfer-Encoding: binary");
  
  readfile($filename);
  
  ?&gt;
  </code></pre>
  
  <p>This overwrites the file test-download.html file and forces a download.</p>
  
  <p><strong>Question:</strong> How can I do this without messing with a file (the test-download.html) on the server?</p>