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

我使用的是rmdir(PATH。“/”。美元价值);要删除一个文件夹,但是,如果里面有文件,我根本不能删除它。


当前回答

您可以尝试如下:

/*
 * 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);
        }
    }
}

其他回答

简单易行…

$dir ='pathtodir';
if (is_dir($dir)) {
  foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename) {
    if ($filename->isDir()) continue;
    unlink($filename);
  }
  rmdir($dir);
}

这个呢?

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

现在至少有两种选择。

Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example: 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); } And if you are using 5.2+ you can use a RecursiveIterator to do it without implementing the recursion yourself: $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);

删除文件夹中的所有文件 到“分离”,水珠(" $目录/ * . * ")); 删除文件夹中所有。*-文件(不带"."和"..") 到“分离”,array_diff(水珠(“目录/美元。*),数组(“目录/美元。”,“目录/美元. .”))) 现在删除文件夹本身 删除文件夹(目录)

这里有一个简单的解决办法

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

    }
   $folder_handler->close();
   rmdir($dirname);