0

I have a small issue regarding a function that I've created. It should delete every directories and sub-directories (and of course, the files in it) but it does absolutely nothing!

function deletedirandfiles($data, $username){

                //$data correspond au chemin clé, cad à images/users

                $dir = opendir($data); // On définit le répertoire dans lequel on souhaite travailler.

                while (false !== ($fichier = readdir($dir))) // On lit chaque fichier du répertoire dans la boucle.
                {
                    if (($fichier == '.') OR ($fichier == '..') OR ($fichier == '.DS_Store') OR ($fichier != $username)){
                    // On ne fait rien pour ne pas les afficher
                    }

                    elseif (is_file($data.'/'.$fichier)){
                        unlink($data.'/'.$fichier);
                    }

                    elseif (is_dir($data.'/'.$fichier)){
                        $foldertoworkin = "$data/$fichier";
                        deletedirandfiles($foldertoworkin, $username); //On lance la recursivité en reappelant la fonction
                        rmdir($data.'/'.$fichier);
                    }

                    else{

                    }

                }

                closedir($dir);

}

In this case: $data = "images/users" and $username = the name of the folder.

Any idea why it does not work ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
TheJailbreakBay
  • 53
  • 1
  • 10

1 Answers1

0

An OS agnostic solution that works with hidden files can be:

public static function delTree($dir) { 
    $files = array_diff(scandir($dir), array('.','..')); 
    foreach ($files as $file) { 
      (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
    } 
    return rmdir($dir); 
} 

You can find more examples at: http://us3.php.net/rmdir

Regards.

mcuadros
  • 4,098
  • 3
  • 37
  • 44