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

前端 未结 8 1790
囚心锁ツ
囚心锁ツ 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: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 );
      }
    }
    

提交回复
热议问题