Advertisement
Guest User

Untitled

a guest
Feb 13th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.45 KB | None | 0 0
  1. <?php
  2.  
  3. function cleanCache($pathToCacheFolder = null, $notAccessedInXDays = null){
  4.     // uncomment the next lines if you want to stop the command if parameters are null
  5.     // without showing any error
  6.     /*
  7.     if ($pathToCacheFolder === null || $notAccessedInXDays == null) {
  8.         return;
  9.     }
  10.     */
  11.     // throw exception if dir doesn't exist
  12.     if ( ! is_dir($pathToCacheFolder)) {
  13.         // if you don't want to show an error if pathToCacheFolder doesn't exist
  14.         // just replace the next line with "return;"
  15.         throw new RuntimeException("Folder '${pathToCacheFolder}' doesn't exist");
  16.     }
  17.     // create our file iterator for the given path
  18.     $iterator = new FileSystemIterator($pathToCacheFolder);
  19.     // ignore . and ..
  20.     $iterator->setFlags(FileSystemIterator::SKIP_DOTS|FileSystemIterator::CURRENT_AS_PATHNAME);
  21.  
  22.     foreach ($iterator as $file) {
  23.         // current time
  24.         $now = new DateTime();
  25.  
  26.         // set file modified datetime
  27.         $filemtime = new DateTime();
  28.         $filemtime->setTimestamp(filemtime($file));
  29.  
  30.         // diff those two
  31.         $diff = $now->diff($filemtime);
  32.  
  33.         $ext = pathinfo($file, PATHINFO_EXTENSION);
  34.  
  35.         // if file extension is one of these
  36.         // and file wasn't modified since $notAccessedInXDays
  37.         if (in_array($ext, array('gif', 'jpg', 'png')) && $diff->format("a") > $notAccessedInXDays) {
  38.             // delete it
  39.             unlink($file);
  40.         }
  41.     }
  42. }
  43.  
  44. // usage example
  45. // delete all jpg,png,gif files that weren't modified since 15 days
  46. // inside "cache" dir
  47. cleanCache('./cache', 15);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement