283

我想知道,删除包含所有文件的目录的最简单方法是什么?

rmdir(PATH . '/' . $value);用来删除一个文件夹,但是,如果里面有文件,我根本无法删除它。

4

34 回答 34

424

现在至少有两种选择。

  1. 在删除文件夹之前,请删除其所有文件和文件夹(这意味着递归!)。这是一个例子:

    public static function deleteDir($dirPath) {
        if (! is_dir($dirPath)) {
            throw new InvalidArgumentException("$dirPath must be a directory");
        }
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
            $dirPath .= '/';
        }
        $files = glob($dirPath . '*', GLOB_MARK);
        foreach ($files as $file) {
            if (is_dir($file)) {
                self::deleteDir($file);
            } else {
                unlink($file);
            }
        }
        rmdir($dirPath);
    }
    
  2. 如果您使用的是 5.2+,则可以使用 RecursiveIterator 来执行此操作,而无需自己实现递归:

    $dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree';
    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it,
                 RecursiveIteratorIterator::CHILD_FIRST);
    foreach($files as $file) {
        if ($file->isDir()){
            rmdir($file->getRealPath());
        } else {
            unlink($file->getRealPath());
        }
    }
    rmdir($dir);
    
于 2010-07-28T03:51:47.877 回答
238

我通常使用它来删除文件夹中的所有文件:

array_map('unlink', glob("$dirname/*.*"));

然后你可以做

rmdir($dirname);
于 2014-10-17T11:24:55.247 回答
98

删除包含所有文件的目录的最简单方法是什么?

system("rm -rf ".escapeshellarg($dir));
于 2010-07-28T04:03:08.287 回答
55

完成这项工作的简短功能:

function deleteDir($path) {
    return is_file($path) ?
            @unlink($path) :
            array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path);
}

我在这样的 Utils 类中使用它:

class Utils {
    public static function deleteDir($path) {
        $class_func = array(__CLASS__, __FUNCTION__);
        return is_file($path) ?
                @unlink($path) :
                array_map($class_func, glob($path.'/*')) == @rmdir($path);
    }
}

权力越大,责任越大:当你调用这个函数时,它会删除从根( /) 开始的文件。作为保障,您可以检查路径是否为空:

function deleteDir($path) {
    if (empty($path)) { 
        return false;
    }
    return is_file($path) ?
            @unlink($path) :
            array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path);
}
于 2011-12-31T13:12:20.273 回答
31

正如在关于 PHP 手册页的大多数投票评论中看到的rmdir()(参见http://php.net/manual/es/function.rmdir.php),glob()函数不返回隐藏文件。 scandir()提供作为解决该问题的替代方案。

那里描述的算法(在我的例子中就像一个魅力)是:

<?php 
    function delTree($dir)
    { 
        $files = array_diff(scandir($dir), array('.', '..')); 

        foreach ($files as $file) { 
            (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
        }

        return rmdir($dir); 
    } 
?>
于 2013-01-25T23:01:45.257 回答
20

你可以使用 Symfony 的文件系统代码):

// composer require symfony/filesystem

use Symfony\Component\Filesystem\Filesystem;

(new Filesystem)->remove($dir);

但是我不能用这种方法删除一些复杂的目录结构,所以首先你应该尝试它以确保它正常工作。


我可以使用 Windows 特定的实现来删除上述目录结构:

$dir = strtr($dir, '/', '\\');
// quotes are important, otherwise one could
// delete "foo" instead of "foo bar"
system('RMDIR /S /Q "'.$dir.'"');


为了完整起见,这是我的旧代码:

function xrmdir($dir) {
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }
        $path = $dir.'/'.$item;
        if (is_dir($path)) {
            xrmdir($path);
        } else {
            unlink($path);
        }
    }
    rmdir($dir);
}
于 2015-05-17T21:09:55.837 回答
19

这是一个较短的版本对我很有用

function deleteDirectory($dirPath) {
    if (is_dir($dirPath)) {
        $objects = scandir($dirPath);
        foreach ($objects as $object) {
            if ($object != "." && $object !="..") {
                if (filetype($dirPath . DIRECTORY_SEPARATOR . $object) == "dir") {
                    deleteDirectory($dirPath . DIRECTORY_SEPARATOR . $object);
                } else {
                    unlink($dirPath . DIRECTORY_SEPARATOR . $object);
                }
            }
        }
    reset($objects);
    rmdir($dirPath);
    }
}
于 2012-11-21T20:49:16.413 回答
10

在这里,您有一个很好且简单的递归来删除源目录中的所有文件,包括该目录:

function delete_dir($src) { 
    $dir = opendir($src);
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                delete_dir($src . '/' . $file); 
            } 
            else { 
                unlink($src . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
    rmdir($src);

}

功能基于为复制目录而进行的递归。您可以在此处找到该功能: 使用 php 将目录的全部内容复制到另一个目录

于 2013-02-23T14:03:47.797 回答
9

我不敢相信有 30 多个答案。递归删除 PHP 中的文件夹可能需要几分钟,具体取决于目录的深度和其中的文件数量!你可以用一行代码做到这一点......

shell_exec("rm -rf " . $dir);

如果您担心删除整个文件系统,请首先确保您的$dir路径正是您想要的。绝不允许用户输入可以直接删除文件的内容,而无需首先对输入进行大量验证。这是基本的编码实践。

于 2021-04-13T11:27:19.690 回答
8

您可以尝试如下:

/*
 * Remove the directory and its content (all files and subdirectories).
 * @param string $dir the directory name
 */
function rmrf($dir) {
    foreach (glob($dir) as $file) {
        if (is_dir($file)) { 
            rmrf("$file/*");
            rmdir($file);
        } else {
            unlink($file);
        }
    }
}
于 2018-11-15T05:54:08.883 回答
6

这个对我有用:

function removeDirectory($path) {
    $files = glob($path . '/*');
    foreach ($files as $file) {
        is_dir($file) ? removeDirectory($file) : unlink($file);
    }
    rmdir($path);
    return;
}
于 2018-03-23T07:55:52.390 回答
5

Linux 服务器的示例:exec('rm -f -r ' . $cache_folder . '/*');

于 2017-07-12T15:00:05.107 回答
4

对我来说最好的解决方案

my_folder_delete("../path/folder");

代码:

function my_folder_delete($path) {
    if(!empty($path) && is_dir($path) ){
        $dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS); //upper dirs are not included,otherwise DISASTER HAPPENS :)
        $files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($files as $f) {if (is_file($f)) {unlink($f);} else {$empty_dirs[] = $f;} } if (!empty($empty_dirs)) {foreach ($empty_dirs as $eachDir) {rmdir($eachDir);}} rmdir($path);
    }
}

ps 记住!
不要将空值传递给任何目录删除函数!!!(总是备份它们,否则有一天你可能会遇到灾难!!)

于 2014-11-26T09:10:03.703 回答
4

那这个呢:

function recursiveDelete($dirPath, $deleteParent = true){
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
        $path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
    }
    if($deleteParent) rmdir($dirPath);
}
于 2015-10-13T10:34:15.503 回答
4

Glob 函数不返回隐藏文件,因此 scandir 在尝试递归删除树时可能更有用。

<?php
public static function delTree($dir) {
   $files = array_diff(scandir($dir), array('.','..'));
    foreach ($files as $file) {
      (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
  }
?>
于 2017-01-04T17:54:53.587 回答
4

我想用@Vijit 的评论来扩展@alcuadrado 的答案,以处理符号链接。首先,使用 getRealPath()。但是,如果您有任何作为文件夹的符号链接,它将失败,因为它会尝试在链接上调用 rmdir - 所以您需要额外检查。

$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
    if ($file->isLink()) {
        unlink($file->getPathname());
    } else if ($file->isDir()){
        rmdir($file->getPathname());
    } else {
        unlink($file->getPathname());
    }
}
rmdir($dir);
于 2017-06-06T14:01:19.640 回答
3

我更喜欢这个,因为它在成功时仍然返回 TRUE,在失败时返回 FALSE,并且它还可以防止空路径可能尝试从 '/*' 中删除所有内容的错误!!:

function deleteDir($path)
{
    return !empty($path) && is_file($path) ?
        @unlink($path) :
        (array_reduce(glob($path.'/*'), function ($r, $i) { return $r && deleteDir($i); }, TRUE)) && @rmdir($path);
}
于 2012-07-26T01:49:56.653 回答
3

使用 DirectoryIterator 相当于以前的答案......</p>

function deleteFolder($rootPath)
{   
    foreach(new DirectoryIterator($rootPath) as $fileToDelete)
    {
        if($fileToDelete->isDot()) continue;
        if ($fileToDelete->isFile())
            unlink($fileToDelete->getPathName());
        if ($fileToDelete->isDir())
            deleteFolder($fileToDelete->getPathName());
    }

    rmdir($rootPath);
}
于 2018-02-16T14:39:34.797 回答
2

像这样的东西?

function delete_folder($folder) {
    $glob = glob($folder);
    foreach ($glob as $g) {
        if (!is_dir($g)) {
            unlink($g);
        } else {
            delete_folder("$g/*");
            rmdir($g);
        }
    }
}
于 2013-01-30T13:13:20.077 回答
2

对 alcuadrado 代码的一点点修改 -glob看不到文件的名称来自点,.htaccess所以我使用 scandir 并且脚本会自行删除 - 检查__FILE__

function deleteDir($dirPath) {
    if (!is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = scandir($dirPath); 
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        if (is_dir($dirPath.$file)) {
            deleteDir($dirPath.$file);
        } else {
            if ($dirPath.$file !== __FILE__) {
                unlink($dirPath.$file);
            }
        }
    }
    rmdir($dirPath);
}
于 2013-12-30T22:51:20.033 回答
2

你可以试试这个简单的 12 行代码来删除文件夹或文件夹文件......快乐编码...... ;) :)

function deleteAll($str) {
    if (is_file($str)) {
        return unlink($str);
    }
    elseif (is_dir($str)) {
        $scan = glob(rtrim($str,'/').'/*');
        foreach($scan as $index=>$path) {
            $this->deleteAll($path);
        }            
        return @rmdir($str);
    }
}
于 2019-07-18T06:42:18.373 回答
1

删除文件夹中的所有文件 删除文件夹中的
array_map('unlink', glob("$directory/*.*"));
所有 .*-文件(不包括:“.”和“..”)
array_map('unlink', array_diff(glob("$directory/.*),array("$directory/.","$directory/..")))
现在删除文件夹本身
rmdir($directory)

于 2015-07-07T07:34:43.470 回答
1

2 美分添加到上面的这个答案,这很好顺便说一句

在您的 glob(或类似)函数扫描/读取目录后,添加条件以检查响应是否为空,否则invalid argument supplied for foreach()将引发警告。所以...

if( ! empty( $files ) )
{
    foreach( $files as $file )
    {
        // do your stuff here...
    }
}

我的全部功能(作为对象方法):

    private function recursiveRemoveDirectory( $directory )
    {
        if( ! is_dir( $directory ) )
        {
            throw new InvalidArgumentException( "$directory must be a directory" );
        }

        if( substr( $directory, strlen( $directory ) - 1, 1 ) != '/' )
        {
            $directory .= '/';
        }

        $files = glob( $directory . "*" );

        if( ! empty( $files ) )
        {
            foreach( $files as $file )
            {
                if( is_dir( $file ) )
                {
                    $this->recursiveRemoveDirectory( $file );
                }
                else
                {
                    unlink( $file );
                }
            }               
        }
        rmdir( $directory );

    } // END recursiveRemoveDirectory()
于 2016-11-29T14:58:21.843 回答
1

这是完美的解决方案:

function unlink_r($from) {
    if (!file_exists($from)) {return false;}
    $dir = opendir($from);
    while (false !== ($file = readdir($dir))) {
        if ($file == '.' OR $file == '..') {continue;}

        if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
            unlink_r($from . DIRECTORY_SEPARATOR . $file);
        }
        else {
            unlink($from . DIRECTORY_SEPARATOR . $file);
        }
    }
    rmdir($from);
    closedir($dir);
    return true;
}
于 2017-12-20T06:48:32.567 回答
1

那这个呢?

function Delete_Directory($Dir) 
{
  if(is_dir($Dir))
  {
      $files = glob( $Dir . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned

      foreach( $files as $file )
      {
          Delete_Directory( $file );      
      }
      if(file_exists($Dir))
      {
          rmdir($Dir);
      }
  } 
  elseif(is_file($Dir)) 
  {
     unlink( $Dir );  
  }
}

参考: https ://paulund.co.uk/php-delete-directory-and-files-in-directory

于 2017-12-25T09:28:13.127 回答
1

你可以复制 YII 助手

$directory (string) - 递归删除。

$options (array) - 用于删除目录。有效选项是: traverseSymlinks:布尔值,是否也应遍历目录的符号链接。默认为false,表示符号链接目录的内容不会被删除。在这种默认情况下,只会删除符号链接。

public static function removeDirectory($directory,$options=array())
{
    if(!isset($options['traverseSymlinks']))
        $options['traverseSymlinks']=false;
    $items=glob($directory.DIRECTORY_SEPARATOR.'{,.}*',GLOB_MARK | GLOB_BRACE);
    foreach($items as $item)
    {
        if(basename($item)=='.' || basename($item)=='..')
            continue;
        if(substr($item,-1)==DIRECTORY_SEPARATOR)
        {
            if(!$options['traverseSymlinks'] && is_link(rtrim($item,DIRECTORY_SEPARATOR)))
                unlink(rtrim($item,DIRECTORY_SEPARATOR));
            else
                self::removeDirectory($item,$options);
        }
        else
            unlink($item);
    }
    if(is_dir($directory=rtrim($directory,'\\/')))
    {
        if(is_link($directory))
            unlink($directory);
        else
            rmdir($directory);
    }
}
于 2019-08-06T12:46:12.223 回答
0
<?php
  function rrmdir($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (filetype($dir."/".$object) == "dir") 
           rrmdir($dir."/".$object); 
        else unlink   ($dir."/".$object);
      }
    }
    reset($objects);
    rmdir($dir);
  }
 }
?>

您是否尝试过来自 php.net 的上述代码

为我工作很好

于 2013-04-03T13:06:49.863 回答
0

对于窗户:

system("rmdir ".escapeshellarg($path) . " /s /q");
于 2013-11-01T16:59:20.940 回答
0

与 Playnox 的解决方案类似,但具有优雅的内置 DirectoryIterator:

function delete_directory($dirPath){
 if(is_dir($dirPath)){
  $objects=new DirectoryIterator($dirPath);
   foreach ($objects as $object){
    if(!$object->isDot()){
     if($object->isDir()){
      delete_directory($object->getPathname());
     }else{
      unlink($object->getPathname());
     }
    }
   }
   rmdir($dirPath);
  }else{
   throw new Exception(__FUNCTION__.'(dirPath): dirPath is not a directory!');
  }
 }
于 2014-10-21T11:20:28.117 回答
0

我不记得我从哪里复制了这个函数,但它看起来没有列出,它对我有用

function rm_rf($path) {
    if (@is_dir($path) && is_writable($path)) {
        $dp = opendir($path);
        while ($ent = readdir($dp)) {
            if ($ent == '.' || $ent == '..') {
                continue;
            }
            $file = $path . DIRECTORY_SEPARATOR . $ent;
            if (@is_dir($file)) {
                rm_rf($file);
            } elseif (is_writable($file)) {
                unlink($file);
            } else {
                echo $file . "is not writable and cannot be removed. Please fix the permission or select a new path.\n";
            }
        }
        closedir($dp);
        return rmdir($path);
    } else {
        return @unlink($path);
    }
}
于 2015-08-12T13:39:48.860 回答
0

简单易行...

$dir ='pathtodir';
if (is_dir($dir)) {
  foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename) {
    if ($filename->isDir()) continue;
    unlink($filename);
  }
  rmdir($dir);
}
于 2016-05-27T11:34:08.887 回答
0

如果您不确定,Given path 是目录或文件,那么您可以使用此功能删除路径

function deletePath($path) {
        if(is_file($path)){
            unlink($path);
        } elseif(is_dir($path)){
            $path = (substr($path, -1) !== DIRECTORY_SEPARATOR) ? $path . DIRECTORY_SEPARATOR : $path;
            $files = glob($path . '*');
            foreach ($files as $file) {
                deleteDirPath($file);
            }
            rmdir($path);
        } else {
            return false;
        }
}
于 2018-07-23T10:01:19.277 回答
-1

这是一个简单的解决方案

$dirname = $_POST['d'];
    $folder_handler = dir($dirname);
    while ($file = $folder_handler->read()) {
        if ($file == "." || $file == "..")
            continue;
        unlink($dirname.'/'.$file);

    }
   $folder_handler->close();
   rmdir($dirname);
于 2013-01-06T15:22:39.523 回答
-5

平台无关代码。

从 PHP.net得到答案

if(PHP_OS === 'Windows')
{
 exec("rd /s /q {$path}");
}
else
{
 exec("rm -rf {$path}");
}
于 2016-01-11T14:10:42.007 回答