title: Delete file after downloading - PHP
body: <p>I am working on Moodle 2.2.1 and have created dynamic.csv files using certain queries. I have created a /tmp/ directory with write permissions in my home directory and using file functions I have created a .csv file thru my code.</p>
  
  <p>Everything works fine with the normal fopen(), fwrite() functions and csv files get created every time dynamically. I have kept these files for downloading for users with this piece of code.</p>
  
  <pre><code>&lt;a href='/moodle/tmp/'".$filename."'&gt; Download &lt;/a&gt;
  </code></pre>
  
  <p>N with this line in .htaccess, the files are downloadable to any one's machine.</p>
  
  <pre><code> AddType application/octet-stream .csv
  </code></pre>
  
  <p>But the problem right now is, every time I load the page,  same .csv files get created with different timestamps. Basically I get a lot many duplicate files with different timestamps in my /tmp/ directory.</p>
  
  <p>Is there a way that on every load of that page, all the existing instances of the files in that folder get deleted and a fresh batch of files are ready for download. So that I do not have duplicate files and just one instance of each file.</p>
  
  <p>If any one can help me with this, I would really appreciate.</p>
  
  <p>Thanks</p>
  
  <p>EDIT: If my code for creating and writing a .csv file is this, then where should I delete the old files with timestamp before an hour and how to retain newest files.</p>
  
  <pre><code> foreach($uniquenames as $uniquename)
   {
  $data = "Header1,Header2,Header3,Header4,Header5\n";
  $filename = $uniquename.'_'.time().'.csv';
  $writepath = $filepath.$filename;
  $fh       = fopen($writepath, 'w');
  $result = $functions-&gt;getFiless();
  foreach($result as $activity)
  {
      if($uniquename == $activity-&gt;quiz)
      {
          $data .= .$somedata.",".$foreachheader."\n";        
      }
      else
      {
  
      }
  }
  fwrite($fh, $data);
  fclose($fh);
  echo "&lt;p&gt;".$uniquename . "&lt;div class='assessment-reportlink'&gt;&lt;a href='/moodle/tmp/".$filename."'&gt; Download &lt;/a&gt;&lt;/p&gt;&lt;/div&gt;";
  </code></pre>
  
  <p>}</p>