3

Can PHP delete expired files? I tried with my code like this, but php delete all the files in the folder my code :

         $dir    = 'images/';
         if (is_dir($dir)) { if ($dh = opendir($dir)) {
         while (($file = readdir($dh)) !== false) {
         if(is_file($dir."/".$file)) { 
         $file_date = date ("d-m-Y", filemtime($dir."/".$file));
         echo $file_date ;
         $file_ch_exp_date = strtotime( $file_date);
         //echo $file_ch_exp_date ;
         echo "<br>";

         if(time() > $file_ch_exp_date) {
            unlink($dir."/".$file); 
         }
            }                
        }            
        closedir($dh);
        }
        }

I have in my folder file that I want to delete :

1.jpg 19.06.2017

2.jpg 19.06.2017

3.jpg 19.06.2017

I don't want to delete

ok.jpg 28.06.2017

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
user1780343
  • 1,439
  • 2
  • 9
  • 10
  • 1
    The filemtime() function returns the last time the file content was modified. So it refer to a past date and I think that for all file the if statment return true and delete it. – Osama Jun 28 '17 at 09:06
  • time() > $file_ch_exp_date seems to be counter-intuitive. You want to remove older files than the expiry date, so you need to do an inverse check of time() < $file_ch_exp_date – Lajos Arpad Jun 28 '17 at 09:13
  • As Osama already pointed out, filemtime returns the last time a file was modified. If you want to check the creation date, then you will need filectime, note the c instead of m in the name. It means creation instead of modification. – Lajos Arpad Jun 28 '17 at 09:15
  • Does this answer your question? [The correct way to delete all files older than 2 days in PHP](https://stackoverflow.com/questions/8965778/the-correct-way-to-delete-all-files-older-than-2-days-in-php) –  Dec 24 '19 at 22:49

1 Answers1

1

you can try this bit of code it may help

      $files = glob(cacheme_directory()."*");
      $now   = time();

      foreach ($files as $file) {
        if (is_file($file)) {
          if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days
            unlink($file);
          }
        }
      }

you can checkout the answer over here its for refrence as shown here