PHP – Remove recursively all expired files and empty subfolder from path

Php coding scriptsBelow you have two useful functions when you want to periodically delete the contents of a folder, especially when working with temporary files, chache files or after uploading some files on server  but regular/scheduled cleaning should be done !

The first two function is recursive (two versions) and the last is interactive. The last has an additional option, if you want even the base folder ($path) to be deleted, then set the third parameter ($selfRemove) to TRUE.

The first function may not delete the basic folder until the second call due to the operating system, but the second one always works correctly.

Remove recursively all expired files and empty subfolder from path

/**
 * Remove recursively all expired files and empty subfolder from path
 * 
 * The $path is deleted if all files and subfolders is removed
 *
 * @param string	$path   The folder path you want to clean
 * @param int		$expire The expiration time after which the files are deleted (seconds)
 */
function recursivelyCleanExpiredFiles($path, $expire=3600) {
  $now = time();
  
  if (is_file($path)) {
    if ($now - filemtime($path) >= $expire ) {
      @unlink($path);
      return 0;
    }
    return 1;
  }
  elseif ( is_dir($path) && !is_link($path) ) {
    $scan = glob(rtrim($path,'/').'/*');
    $notempty = 0;
    foreach($scan as $index=>$path) {
      $notempty += recursivelyCleanExpiredFiles($path, $expire);
    }
    
    if ($notempty == 0)			
      @rmdir($path);
    
    return $notempty;
  }	
}

v.2 (recursively)

/**
 * Remove recursively all expired files and empty subfolder from path
 * 
 * The $path is deleted if all files and subfolders is removed
 *
 * @param string	$path   The folder path you want to clean
 * @param int		$expire The expiration time after which the files are deleted (seconds)
 */
function recursivelyCleanExpiredFiles($path, $expire=3600) {
  $now = time();
  
    $folder = opendir($path);
    while(false !== ( $file = readdir($folder)) ) {
    if (( $file == '.' ) || ( $file == '..' )) 
      continue;
            
      $fullPath = $path . '/' . $file;
      if ( is_dir($fullPath) ) {
        recursivelyCleanExpiredFiles($fullPath, $expire);
      }
      elseif ( $now - filemtime($fullPath) >= $expire )  {
        @unlink($fullPath);
      }        
    }
    closedir($folder);
    @rmdir($path);
}

Remove all expired files and empty subfolder from path

/**
 * Remove all expired files and empty subfolder from path
 * 
 * By default the root directory is maintained, it is not deleted. 
 * To delete the folder and not just its subfolders and files, the last parameter must be true,
 * example: CleanExpiredFiles($mypath, 1800, true);
 *
 * @param string	$path   The folder path you want to clean
 * @param int		$expire The expiration time after which the files are deleted (seconds)
 * @param bool		$selfRemove The flag that determines whether the $path is also deleted if there is no more content inside it.
 */
function CleanExpiredFiles($path, $expire=3600, $selfRemove=false) {
  $files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::CHILD_FIRST
  );
  
  $now = time();

  foreach ($files as $fileinfo) {		
    if ($fileinfo->isDir()) {
      @rmdir($fileinfo->getRealPath());
    } else {
      $fname = $fileinfo->getRealPath();
      if ($now - filemtime($fname) >= $expire )
        @unlink($fname);
    }
  }

  if ($selfRemove)
    @rmdir($path);
}

Happy coding for all !

byrev Written by:

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *