title: Laravel download file from php output buffer VS. private storage folder | security
body: <p>A user can download query results in CSV format. The file is small (a few KB), but the contents are important.</p>
  
  <p>The first approach is to use php output buffer <code>php://</code>:</p>
  
  <pre><code>$callback = function() use ($result, $columns) {
      $file = fopen('php://output', 'w');
      fputcsv($file, $columns);
  
      foreach($result as $res) {
          fputcsv($file, array($res-&gt;from_user, $res-&gt;to_user, $res-&gt;message, $res-&gt;date_added));
      }
      fclose($file);
  };
  
  return response()-&gt;stream($callback, 200, $headers);
  </code></pre>
  
  <p>The second approach is to create a new folder in laravels storage system and set it to private and download the file from there. You could even delete the file after the download:</p>
  
  <pre><code>'csv' =&gt; [
      'driver' =&gt; 'local',
      'root' =&gt; storage_path('csv'),
      'visibility' =&gt; 'private',
  ],
  </code></pre>
  
  <p>Here is the create/download code:</p>
  
  <pre><code>$file = fopen('../storage/csv/file.csv', 'w');
  fputcsv($file, $columns);
  
  foreach($result as $res) {
      fputcsv($file, array($res-&gt;from_user, $res-&gt;to_user, $res-&gt;message, $res-&gt;date_added));
  }
  fclose($file);
  
  return response()-&gt;make(Storage::disk('csv')-&gt;get('file.csv'), 200, $headers);
  </code></pre>
  
  <p>This return will instantly delete the file after the download:</p>
  
  <pre><code>return response()-&gt;download(Storage::disk('csv')-&gt;path('file.csv'))
  -&gt;deleteFileAfterSend(true);
  </code></pre>
  
  <p>What would be more secure? What is the better approach? I am currently leaning towards the second approach with the storage.</p>