-1

Function:

function scandir_recursive($dir) {
    $items = scandir($dir);

    foreach($items as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        $file = $dir . '/' . $item;
        echo "$file<br />";

        if (is_dir($file)) {
            scandir_recursive($file);
        }
    }
}
scandir_recursive($path);

Output:

EEAOC/EN/1001/data
EEAOC/EN/1001/data/New Text Document.txt
EEAOC/EN/1001/data/troll.txt
EEAOC/EN/1002/data
EEAOC/EN/1002/data/New Text Document.txt
EEAOC/EN/1002/data/troll.txt
EEAOC/EN/1003/data
EEAOC/EN/1003/data/New Text Document.txt
EEAOC/EN/1003/data/troll.txt
EEAOC/EN/1004/data
EEAOC/EN/1004/data/New Text Document.txt
EEAOC/EN/1004/data/troll.txt

Is it possible to delete those empty directories and keep files? such deleting EEAOC/EN/1001/data &EEAOC/EN/1002/data& EEAOC/EN/1003/data &EEAOC/EN/1004/data

I want to keep remaining how?

Lorenz Lo Sauer
  • 23,698
  • 16
  • 85
  • 87

1 Answers1

0

As shown from your function-output, the directories are not empty.

I suppose that the data is of low value and just needs to be backed up. I assume you are running Linux from your choice of a slash rather than a backslash. Naturally directories incur links or inodes, with metadata, which in linux can be checked via

df -hi 

The Inode-Ids of files can be shown via the -i flag of ls

ls -i filename
ls -iltr
ls -ltri `echo $HOME`

Inodes take up space, and introduce overhead in file-system operations. So much to the motivation to remove the directories.

PHP's rmdir function to remove directories requires that The directory must be empty, and the relevant permissions must permit this. It is also non-recursive.

  • Approach 1: flatten filenames and move the files to a backup directory, then remove the empty directories
  • Approach 2: incrementally archive and remove the directories

#Approach 1
Your choice should depend on how easy and frequent your file access occurs.

function scandir_recursive($dir) { $items = scandir($dir);

foreach($items as $item) {
    if ($item == '.' || $item == '..') {
        continue;
    }

    $file = $dir . '/' . $item;
    $fnameflat = $dir . '_' . $item;
    echo "$file<br />\n";
    if (is_dir($file)) {
        scandir_recursive($file);
    }
    if(is_file($file)){
        rename($file, '~/backup/'.$fnameflat);
    }
}

} scandir_recursive($path);

Afterwards use this function by SeniorDev, to unlink files and directories, or run

`exec("rmdir -rf $path")`

This is not recommended.

#Approach 2

Archive the directory using exec("tar -cvzf backup".date().".tar.gz $path"); or using php.

Then remove the directory aferwards, as described in #1.

Community
  • 1
  • 1
Lorenz Lo Sauer
  • 23,698
  • 16
  • 85
  • 87