简体   繁体   中英

PHP Delete all files that are empty in a Directory and any sub directories

This is what I have but its not working nor giving me an errors:

$MyDir = "C:/some_folder/"; 

// DELETE ALL EMPTY FILES
$filesDVA = glob($MyDir.'*'); // get all file names
foreach($filesDVA as $file){ // iterate files
  if(empty($file))
    unlink($file); // delete file
}

I would like to delete the empty files that are in the main directory and sub directories and if possible check if the directory is empty also and if it is delete it too.

UPDATE:

foreach (glob($MyDir . '*') as $file) {
    if (is_writable($file) && filesize($file) < (1024 * 1)) {
        unlink($file);
    }
}

It removes the empty files (or files that are less than 1kb but it gives me an error when trying to access the directories saying Permission denied for each directory, so it will NOT delete the empty directories or the files that are within the sub directories.

empty($file) doesn't check that the file referenced by $file is empty, it checks that the variable $file is empty. Ie, if $file contains an empty string "" or null then empty($file) will return true. Since your $file contains a non-empty string (the name of the file), empty($file) will always return false, regardless of the file contents. You want to check that filesize($file) is zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM