How to delete files from directory based on creation date in php?

前端 未结 8 1683
囚心锁ツ
囚心锁ツ 2020-11-29 03:52

I have a cache folder that stores html files. They are overwritten when needed, but a lot of the time, rarely used pages are cached in there also, that just end up using sp

相关标签:
8条回答
  • 2020-11-29 04:27
    /* Detele Cache Files Here */
    $dir = "cache/"; /** define the directory **/
    
    /*** cycle through all files in the directory ***/
    foreach (glob($dir."*") as $file) {
    //foreach (glob($dir.'*.*') as $file){
    
    /*** if file is 24 hours (86400 seconds) old then delete it ***/
    if (filemtime($file) < time() - 3600) { // 1 hour
        unlink($file);
        }
    }
    

    I am using this, hope it helps.

    0 讨论(0)
  • 2020-11-29 04:35

    It should be

    if((time()-$filelastmodified) > 24*3600 && is_file($file))
    

    to avoid errors for the . and .. directories.

    0 讨论(0)
  • 2020-11-29 04:38
    $directory = $_SERVER['DOCUMENT_ROOT'].'/pathfromRoot/';
    
    $files = array_slice(scandir($directory), 2);
    foreach($files as $file)
    {
        // $extension      = substr($file, -3, 3); 
        // if ($extension == 'jpg') // in case you only want specific files deleted
        // {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        // dd($days);
        if ($days->days > 180) 
        { 
            unlink($directory.$file);
        }
         // } 
    }
    
    0 讨论(0)
  • 2020-11-29 04:42

    Try SplIterators

    // setup timezone and get timestamp for yesterday
    date_default_timezone_set('Europe/Berlin'); // change to yours
    $yesterday = strtotime('-1 day', time());
    
    // setup path to cache dir and initialize iterator
    $path      = realpath('/path/to/files'); // change to yours
    $objects   = new RecursiveIteratorIterator(
                     new RecursiveDirectoryIterator($path));
    
    // iterate over files in directory and delete them
    foreach($objects as $name => $object){
        if ($object->isFile() && ($object->getCTime() < $yesterday)) {
            // unlink($object);
            echo PHP_EOL, 'deleted ' . $object;
        }
    }
    

    Creation Time is only available on Windows.

    0 讨论(0)
  • 2020-11-29 04:42

    just to note Gordon's time comparison (see above: https://stackoverflow.com/a/2205833/1875965) is the only correct one when comparing to 'days' rather than '24 hours', as not all days have 24 hours (summertime/wintertime etc).

    E.g. use

    // setup timezone and get timestamp for yesterday
    date_default_timezone_set('Europe/Berlin'); // change as appropriate
    $yesterday = strtotime('-1 day', time());
    

    when comparing the file date.

    This may not be a big issue, but can lead to unexpected behaviour when you're working with weeks/months etc. I found it best to stick to using the above method as it'll make any process involving dates/times consistent and avoid confusion.

    Also check what the timezone is for the file dates, as sometimes the default for PHP differs from the system timezone.

    Kind regards, Sandra.

    0 讨论(0)
  • 2020-11-29 04:44

    The below function lists the file based on their creation date:

    private function listdir_by_date( $dir ){
      $h = opendir( $dir );
      $_list = array();
      while( $file = readdir( $h ) ){
        if( $file != '.' and $file != '..' ){
          $ctime = filectime( $dir . $file );
          $_list[ $file ] = $ctime;
        }
      }
      closedir( $h );
      krsort( $_list );
      return $_list;
    }
    

    Example:

    $_list = listdir_by_date($dir);
    

    Now you can loop through the list to see their dates and delete accordingly:

    $now = time();
    $days = 1;
    foreach( $_list as $file => $exp ){
      if( $exp < $now-60*60*24*$days ){
        unlink( $dir . $file );
      }
    }
    
    0 讨论(0)
提交回复
热议问题