简体   繁体   中英

Deleting Directory Contents & SubDirectory Contents

I've set up some PHP to delete a directory, it's contents, and any subdirectory and its contents... I'm new to PHP so I'm most definitely doing something WRONG or am doing something in the most inefficient way.

Looking for some references or suggestion on how to do this better...

By the way, this code works fine. Using PHP 5.3.8.

chmod($main_dir, 0755);
if ($handle = opendir($main_dir)) {
    while (false !== ($entry = readdir($handle))) { 
        $absolute_path = $main_dir.'/'.$entry;
        if ($entry != "." && $entry != "..") {      
            chmod($absolute_path, 0755);
            unlink($absolute_path);

            //check if any folders exist, then delete files within
            if (file_exists($absolute_path) && is_dir($absolute_path)) {
                if ($child_handle = opendir($absolute_path)) {
                    while (false !== ($child_entry = readdir($child_handle))) {             
                    $child_absolute_path = $absolute_path.'/'.$child_entry;
                        if ($child_entry != "." && $child_entry != "..") {              
                            chmod($child_absolute_path, 0755);
                            unlink($child_absolute_path);
                        }
                    }
                    closedir($child_handle);
                }
            }
            rmdir($absolute_path);
        }
    }
    closedir($handle);
}
rmdir($main_dir);

Any thoughts? Much appreciated! Im using PHP 5.3.8

You can use RecursiveDirectoryIterator to list all files and folders then delete them. Please Note that you have to use RecursiveIteratorIterator::CHILD_FIRST so that the files are deleted before the folder.

$dir = __DIR__ . "/test";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}

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