简体   繁体   English

如何使用PHP中的文件夹删除文件夹中的所有文件?

[英]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? 如何用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");
                    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM