php PHP的递归删除目录函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1407338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:26:42  来源:igfitidea点击:

A recursive remove directory function for PHP?

phprecursiondirectory

提问by rhodesjason

I am using PHP to move the contents of a images subfolder

我正在使用 PHP 移动图像子文件夹的内容

GalleryName/images/

画廊名称/图片/

into another folder. After the move, I need to delete the GalleryName directory and everything else inside it.

到另一个文件夹。移动后,我需要删除 GalleryName 目录和其中的所有其他内容

I know that rmdir()won't work unless the directory is empty. I've spent a while trying to build a recursive function to scandir()starting from the top and then unlink()if it's a file and scandir()if it's a directory, then rmdir()each empty directory as I go.

我知道rmdir()除非目录为空,否则这将不起作用。我花了一段时间试图构建一个递归函数,scandir()从顶部开始,然后unlink()如果它是一个文件,scandir()如果它是一个目录,那么rmdir()我去每个空目录。

So far it's not working exactly right, and I began to think -- isn't this a ridiculously simple function that PHP should be able to do?Removing a directory?

到目前为止,它的工作并不完全正确,我开始思考——这难道不是 PHP 应该能够做到的一个非常简单的函数吗?删除目录?

So is there something I'm missing? Or is there at least a proven function that people use for this action?

那么有什么我想念的吗?或者至少有一个经过验证的功能可供人们用于此操作?

Any help would be appreciated.

任何帮助,将不胜感激。

PS I trust you all here more than the comments on the php.net site -- there are hundreds of functions there but I am interested to hear if any of you here recommend one over others.

PS 我比 php.net 站点上的评论更相信你们所有人——那里有数百个功能,但我很想听听你们中是否有人推荐一个而不是其他功能。

回答by barbushin

What about this?

那这个呢?

foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
        $path->isDir() && !$path->isLink() ? rmdir($path->getPathname()) : unlink($path->getPathname());
}
rmdir($dirPath);

回答by rhodesjason

This is the recursive function I've created/modifed and that finally seems to be working. Hopefully there isn't anything too dangerous in it.

这是我创建/修改的递归函数,它最终似乎起作用了。希望里面没有什么太危险的东西。

function destroy_dir($dir) { 
    if (!is_dir($dir) || is_link($dir)) return unlink($dir); 
    foreach (scandir($dir) as $file) { 
        if ($file == '.' || $file == '..') continue; 
        if (!destroy_dir($dir . DIRECTORY_SEPARATOR . $file)) { 
            chmod($dir . DIRECTORY_SEPARATOR . $file, 0777); 
            if (!destroy_dir($dir . DIRECTORY_SEPARATOR . $file)) return false; 
        }; 
    } 
    return rmdir($dir); 
} 

回答by Gabriel Guelfi

If the server of application runs linux, just use the shell_exec() function, and provide it the rm -R command, like this:

如果应用程序的服务器运行的是 linux,只需使用 shell_exec() 函数,并为其提供 rm -R 命令,如下所示:

    $realPath = realpath($dir_path);

    if($realPath === FALSE){
         throw new \Exception('Directory does not exist');
    }

    shell_exec("rm ". escapeshellarg($realPath) ." -R");

Explanation:

解释:

Removes the specified directory recursively only if the path exists and escapes the path so that it can only be used as a shell argument to avoid shell command injection.

仅当路径存在时递归删除指定目录并转义路径,使其只能用作 shell 参数以避免 shell 命令注入。

If you wouldnt use escapeshellargone could execute commands by naming the directory to be removed after a command.

如果您不使用,escapeshellarg则可以通过在命令后命名要删除的目录来执行命令。

回答by David Newcomb

There is another thread with more examples here: How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

这里还有另一个包含更多示例的线程: How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

If you are using Yii then you can leave it to the framework:

如果你使用 Yii,那么你可以把它留给框架:

CFileHelper::removeDirectory($my_directory);

回答by user1680948

I prefer an enhaced method derived from the php help pages http://php.net/manual/en/function.rmdir.php#115598

我更喜欢从 php 帮助页面http://php.net/manual/en/function.rmdir.php#115598派生的增强方法

 // check accidential empty, root or relative pathes
 if (!empty($path) && ...)
 {
  if (PHP_OS === 'Windows')
  {
    exec('rd /s /q "'.$path.'"');
  }
  else
  {
      exec('rm -rf "'.$path.'"');
  }
}
else
{
    error_log('path not valid:$path'.var_export($path, true));
}

reasons for my decision:

我的决定的原因:

  • less code
  • speed
  • keep it simple
  • 更少的代码
  • 速度
  • 把事情简单化

回答by yousef

public static function rrmdir($dir)
{
    if (is_dir($dir)) {
        $files = scandir($dir);
        foreach ($files as $file) {
            if ($file != "." && $file != "..") {
                if (filetype($dir . "/" . $file) == "dir")
                    self::rrmdir($dir . "/" . $file);
                else
                    unlink($dir . "/" . $file);
            }
        }
        reset($files);
        rmdir($dir);
    }
}

回答by Aram Kocharyan

I've adapted a function which handles hidden unix files with the dot prefix and uses glob:

我改编了一个函数,它处理带有点前缀的隐藏 unix 文件并使用 glob:

public static function deleteDir($path) {
    if (!is_dir($path)) {
        throw new InvalidArgumentException("$path is not a directory");
    }
    if (substr($path, strlen($path) - 1, 1) != '/') {
        $path .= '/';
    }
    $dotfiles = glob($path . '.*', GLOB_MARK);
    $files = glob($path . '*', GLOB_MARK);
    $files = array_merge($files, $dotfiles);
    foreach ($files as $file) {
        if (basename($file) == '.' || basename($file) == '..') {
            continue;
        } else if (is_dir($file)) {
            self::deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($path);
}