简体   繁体   中英

How to delete all files in a folder with the folder in PHP?

How would I delete a folder including it's contents with PHP? I know I would use some form of a loop but am not sure what type or what approach I would have to take. I use the following to delete files and want to incorporate it in there:

if(isset($_REQUEST['DelFile'])) {
    $DeleteFile = $_REQUEST['DelFile'];
    if(file_exists($directory.$DeleteFile)) {
        @unlink($directory.$DeleteFile);
        rmdir($directory.$DeleteFile);
        $files = glob($directory . $file); // get all file names

        foreach($files as $file){ // iterate files
            if(is_file($file))
            unlink($file); // delete file
        }
        @header("location:interface.php?msg=1");

    } else @header("location:interface.php?msg=2");
}

为什么不运行rm -rf $directory

system("rm -rf $directory");

You may try this code to get all files in folder then unlink all files using loop

$files = glob('uploads/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file))
    unlink($file); // delete file
}

All I had to do was setup a loop that will delete the files. After the loop I delete the directories.

if(isset($_REQUEST['DelFile_folder'])) {
                        $DeleteFile = $_REQUEST['DelFile_folder'];
                        if(file_exists($directory.$DeleteFile)) {
                            @unlink($directory.$DeleteFile.'/index.php');
                            rmdir($directory.$DeleteFile . '/uploads/' . $_SESSION['user']);
                            rmdir($directory.$DeleteFile . '/uploads');
                            rmdir($directory.$DeleteFile);
                            $dir = 'uploads/' . $_SESSION['user'] . '/' . $DeleteFile . '/uploads/'; 
                            $dirHandle = opendir($dir); 
                            while ($file = readdir($dirHandle)) { 
                                if(!is_dir($file)) { 
                                    unlink ("$dir"."$file");
                                }
                            }
                            closedir($dirHandle);

                            @header("location:interface.php?msg=1");
                        } else @header("location:interface.php?msg=2");
                    }

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