PHP: Unlink All Files Within A Directory, and then Deleting That Directory

NoodleOfDeath picture NoodleOfDeath · Jun 29, 2012 · Viewed 74.4k times · Source

I there a way I can use RegExp or Wildcard searches to quickly delete all files within a folder, and then remove that folder in PHP, WITHOUT using the "exec" command? My server does not give me authorization to use that command. A simple loop of some kind would suffice.

I need something that would accomplish the logic behind the following statement, but obviously, would be valid:


$dir = "/home/dir"
unlink($dir . "/*"); # "*" being a match for all strings
rmdir($dir);

Answer

Lusitanian picture Lusitanian · Jun 29, 2012

Use glob to find all files matching a pattern.

function recursiveRemoveDirectory($directory)
{
    foreach(glob("{$directory}/*") as $file)
    {
        if(is_dir($file)) { 
            recursiveRemoveDirectory($file);
        } else {
            unlink($file);
        }
    }
    rmdir($directory);
}