Delete directory with files in it?

2019-01-01 12:18发布

I wonder, what's the easiest way to delete a directory with all its files in it?

I'm using rmdir(PATH . '/' . $value); to delete a folder, however, if there are files inside of it, I simply can't delete it.

标签: php rmdir
30条回答
还给你的自由
2楼-- · 2019-01-01 12:37

Litle bit modify of alcuadrado's code - glob don't see files with name from points like .htaccess so I use scandir and script deletes itself - check __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);
}
查看更多
大哥的爱人
3楼-- · 2019-01-01 12:37

For windows:

system("rmdir ".escapeshellarg($path) . " /s /q");
查看更多
看淡一切
4楼-- · 2019-01-01 12:37

Here is a simple solution

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

    }
   $folder_handler->close();
   rmdir($dirname);
查看更多
高级女魔头
5楼-- · 2019-01-01 12:38

This is a shorter Version works great to me

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);
    }
}
查看更多
十年一品温如言
6楼-- · 2019-01-01 12:38

Like Playnox's solution, but with the elegant built-in 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!');
  }
 }
查看更多
琉璃瓶的回忆
7楼-- · 2019-01-01 12:40

what's the easiest way to delete a directory with all it's files in it?

system("rm -rf ".escapeshellarg($dir));
查看更多
登录 后发表回答