user1780343
user1780343

Reputation: 1649

delete expired file with php code

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

Upvotes: 3

Views: 1203

Answers (1)

Riddhish Bhayani
Riddhish Bhayani

Reputation: 202

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

Upvotes: 1

Related Questions