title: PHP create and download ZIP on the fly
body: <p>I'm creating a ZIP file with several scripts in it (for example: <em>test.php</em>, <em>functions.js</em> and <em>style.css</em>).</p>
  
  <p>The scripts works just fine, the only problem is that the ZIP file gets placed on my webserver. Is there a way to prevent this? I've read multiple similar questions: <a href="https://stackoverflow.com/questions/4357073/on-the-fly-zipping-streaming-of-large-files-in-php-or-otherwise">this one</a> seems to work, but I can't figure it out how to use that. </p>
  
  <p>So, I wan't to delete the file after it has been placed (even if user aborts it) or (even better) that my scripts never puts the file on the webserver.</p>
  
  <p><strong>download.php</strong></p>
  
  <pre><code>$scriptId = checkNumeric($_GET['sid']);
  
  //Check if user has access to the script
  if(isLoggedIn() &amp;&amp; hasScriptAccess($scriptId))  {
  
      //Create ZIP
      $zip = new ZipArchive();
      $zipName = "script.zip";
  
      if ($zip-&gt;open($zipName, ZIPARCHIVE::CREATE)!== TRUE) {
          exit(); //Something went wrong while creating the ZIP
      }
  
      //Get associated codes
      $query = $mysqli-&gt;query("SELECT * FROM code WHERE script_id = '{$scriptId}'");
      while($code = $query-&gt;fetch_assoc()) {
          $filename = $code['title'];
          $content = $code['code'];
  
          //Add file to ZIP
          $zip-&gt;addFromString($filename, $content);
      }
  
      $zip-&gt;close();
  
      //Set headers
      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Cache-Control: public");
      header("Content-Description: File Transfer");
      header("Content-type: application/octet-stream");
      header("Content-Disposition: attachment; filename='" . $zipName . "'");
      header("Content-Transfer-Encoding: binary");
      header("Content-Length: " . filesize($zipName));
  
      clearstatcache(); //Make sure the file size isn't cached
      readfile($zipName); //Output the file
      $zip-&gt;deleteName($zipName);
  }
  </code></pre>