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

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


当前回答

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

其他回答

现在至少有两种选择。

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);

以Linux服务器为例:exec('rm -f -r '。cache_folder美元。“/ *”);

类似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!');
  }
 }
<?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吗

为我工作吧

这里有一个完美的解决方案:

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;
}