rmdir

(PHP 4, PHP 5)

rmdirRemoves directory

Description

bool rmdir ( string $dirname [, resource $context ] )

Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this. A E_WARNING level error will be generated on failure.

Parameters

dirname

Path to the directory.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.0.0 As of PHP 5.0.0 rmdir() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support rmdir().

Examples

Example #1 rmdir() example

<?php
if (!is_dir('examples')) {
    
mkdir('examples');
}

rmdir('examples');
?>

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

Коментарии

I've noticed that when using this command on a windows platform you may encounter a permissions error which may seem unwarranted. This commonly occurs if you are or were using a program to edit something in the to be deleted folder and either the item is still in the folder or the program that was accessing the file in that folder is still running(causing it to hold onto the folder).

SO... if you get a permissions error and there shouldn't be an issue with folder permissions check if there are files in there then check if there is a program running that is or was using a file that was in that folder and kill it.
2007-12-18 12:16:06
http://php5.kiev.ua/manual/ru/function.rmdir.html
In case you're trying to rmdir() and you keep getting 'Permission denied' errors, make sure you don't have the directory still open after using opendir(). Especially when writing recursive functions for deleting directories, make sure you have closedir() BEFORE rmdir().
2008-08-08 06:21:00
http://php5.kiev.ua/manual/ru/function.rmdir.html
A patch to previous script to make sure rights for deletion is set:

<?php
//Delete folder function
function deleteDirectory($dir) {
    if (!
file_exists($dir)) return true;
    if (!
is_dir($dir) || is_link($dir)) return unlink($dir);
        foreach (
scandir($dir) as $item) {
            if (
$item == '.' || $item == '..') continue;
            if (!
deleteDirectory($dir "/" $item)) {
               
chmod($dir "/" $item0777);
                if (!
deleteDirectory($dir "/" $item)) return false;
            };
        }
        return 
rmdir($dir);
    }
?>

[EDITOR NOTE: "Credits to erkethan at free dot fr." - thiago]
2009-07-07 00:08:49
http://php5.kiev.ua/manual/ru/function.rmdir.html
Sometimes you would face situations in which rmdir($dirname) would give "permission denied" errors though you may have changed $dirname permissions. In such situations just change the permissions of the directory which contains $dirname and rmdir($dirname) would work like a charm.
Say you use rmdir('dirr'); then change the permissions of the folder that contains 'dirr'.
2009-10-09 00:52:21
http://php5.kiev.ua/manual/ru/function.rmdir.html
Say, you're working on Windows and continue to get a permission's error without a reason. Then it may be that a different Windows program is working on the folder (see earlier notes also). In the case that you can't find that program, the line

<?php closedir(opendir($dirname)); ?>

may solve the problem!
Make sure to write this before rmdir($dirname);.
2010-01-16 19:40:05
http://php5.kiev.ua/manual/ru/function.rmdir.html
The function delTree is dangerous when you dont take really care. I for example always deleted a temporary directory with it. Everthing went fine until the moment where the var containing this temporary directory wasnt set. The var didnt contain the path but an empty string. The function delTree  was called and deleted all the files at my host!
So dont use this function when you dont have a proper handling coded. Dont think about using this function only for testing without such a handling.
Luckily nothing is lost because I had the local copy...
2010-04-28 07:15:56
http://php5.kiev.ua/manual/ru/function.rmdir.html
Автор:
This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move.

Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.

<?php
function deleteAll($directory$empty false) {
    if(
substr($directory,-1) == "/") {
       
$directory substr($directory,0,-1);
    }

    if(!
file_exists($directory) || !is_dir($directory)) {
        return 
false;
    } elseif(!
is_readable($directory)) {
        return 
false;
    } else {
       
$directoryHandle opendir($directory);
       
        while (
$contents readdir($directoryHandle)) {
            if(
$contents != '.' && $contents != '..') {
               
$path $directory "/" $contents;
               
                if(
is_dir($path)) {
                   
deleteAll($path);
                } else {
                   
unlink($path);
                }
            }
        }
       
       
closedir($directoryHandle);

        if(
$empty == false) {
            if(!
rmdir($directory)) {
                return 
false;
            }
        }
       
        return 
true;
    }
}
?>
2010-06-18 18:30:23
http://php5.kiev.ua/manual/ru/function.rmdir.html
Another simple way to recursively delete a directory that is not empty:

<?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);
   }
 }
?>
2010-06-26 17:00:06
http://php5.kiev.ua/manual/ru/function.rmdir.html
if you get this problem Permission denied in windows testing your site maybe this will resolve the problem 

<?php
if(file_exists($path.'/Thumbs.db')){
   
unlink($path.'/Thumbs.db');
}
?>

and then

<?php rmdir($path); ?>
2011-06-27 06:38:41
http://php5.kiev.ua/manual/ru/function.rmdir.html
This issue has been driving me nuts for hours.

I am running PHP on IIS, I had the wincache module installed, when running a recursive delete a certain folder would get "stuck" and throw permissions errors.  I was not able to delete them with PHP or in windows itself.  The only way to delete the folder was to wait 5 min and run the script again, or stop the IIS server and the folder would delete on its own.  Disabling the wincachce module resolved the issue.

Hope this helps.
2011-08-08 16:50:49
http://php5.kiev.ua/manual/ru/function.rmdir.html
Автор:
Function deleteAll given by O S on 18-Jun-2010 11:30 will fail at line

while ($contents = readdir($directoryHandle)) {...

if a folder named 0 (zero) is found during traversing the hierarchy
2011-11-21 02:44:11
http://php5.kiev.ua/manual/ru/function.rmdir.html
Concise way to recursively remove a directory:

<?php
# recursively remove a directory
function rrmdir($dir) {
    foreach(
glob($dir '/*') as $file) {
        if(
is_dir($file))
           
rrmdir($file);
        else
           
unlink($file);
    }
   
rmdir($dir);
}
?>
2012-03-29 22:10:54
http://php5.kiev.ua/manual/ru/function.rmdir.html
Автор:
I also ran into the permissions issue in Windows when deleting a folder and the solution was to close all editors which had files opened which were located in the folder structure.
2012-09-01 23:29:55
http://php5.kiev.ua/manual/ru/function.rmdir.html
Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.

<?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);
  }
?>
2012-10-29 00:36:22
http://php5.kiev.ua/manual/ru/function.rmdir.html
It is rather dangerous to recurse into symbolically linked directories. The delTree should be modified to check for links.

<?php 
public static function delTree($dir) { 
   
$files array_diff(scandir($dir), array('.','..')); 
    foreach (
$files as $file) { 
      (
is_dir("$dir/$file") && !is_link($dir)) ? delTree("$dir/$file") : unlink("$dir/$file"); 
    } 
    return 
rmdir($dir); 
  } 
?>
2014-01-22 00:10:53
http://php5.kiev.ua/manual/ru/function.rmdir.html
Автор:
Keep in mind that if you know what your host OS is, you can always just call the appropriate system call using exec() or the like. For example:

exec('rmdir folder-to-delete /s /q'); //windows
exec('rmdir -rf folder-to-delete'); //OS X/*nix?
2014-05-21 22:13:15
http://php5.kiev.ua/manual/ru/function.rmdir.html
Автор:
Works fine, tested on PHP 5.4(EasyPHP server)
function deletedir($dir)
    {
        if (is_dir($dir))
        { 
            $files = scandir($dir); 
            foreach ($files as $file)
            { 
                if ($file != "." && $file != "..")
                { 
                    if (filetype($dir."/".$file) == "dir")
                    {
                        $this->deletedir($dir."/".$file);
                    }
                    else
                    {
                        unlink($dir."/".$file); 
                    }
                } 
            } 
            reset($objects); 
            if(rmdir($dir))
            {
                return 'deleted successfully!';
            }
            else
            {
                return 'delete failed!';
            }
        } 
        else
        {
            return 'doesn\'t exist or inaccessible!';
        }
    }
Something to note:
You have to take care of file permission if necessary
2014-08-27 09:42:39
http://php5.kiev.ua/manual/ru/function.rmdir.html
function unlinkDir($dir)
{
    $dirs = array($dir);
    $files = array() ;
    for($i=0;;$i++)
    {
        if(isset($dirs[$i]))
            $dir =  $dirs[$i];
        else
            break ;
   
        if($openDir = opendir($dir))
        {
            while($readDir = @readdir($openDir))
            {
                if($readDir != "." && $readDir != "..")
                {
                 
                    if(is_dir($dir."/".$readDir))
                    {
                        $dirs[] = $dir."/".$readDir ;
                    }
                    else
                    {
                       
                        $files[] = $dir."/".$readDir ; 
                    }
                }
            }
       
        }
       
    }
   
   
   
    foreach($files as $file)
    {
        unlink($file) ;
     
    }
    $dirs = array_reverse($dirs) ;
    foreach($dirs as $dir)
    {
        rmdir($dir) ;
    }
   
}
2014-10-01 13:32:51
http://php5.kiev.ua/manual/ru/function.rmdir.html
I was working on some Dataoperation, and just wanted to share an OOP method with you.

It just removes any contents of a Directory but not the target Directory itself! Its really nice if you want to clean a BackupDirectory or Log.

Also you can test on it if something went wrong or if it just done its Work!

I have it in a FileHandler class for example, enjoy!

<?php 

 
public function deleteContent($path){
      try{
       
$iterator = new DirectoryIterator($path);
        foreach ( 
$iterator as $fileinfo ) {
          if(
$fileinfo->isDot())continue;
          if(
$fileinfo->isDir()){
            if(
deleteContent($fileinfo->getPathname()))
              @
rmdir($fileinfo->getPathname());
          }
          if(
$fileinfo->isFile()){
            @
unlink($fileinfo->getPathname());
          }
        }
      } catch ( 
Exception $e ){
         
// write log
         
return false;
      }
      return 
true;
    }

?>
2015-01-26 10:31:42
http://php5.kiev.ua/manual/ru/function.rmdir.html
some implementations of recursive folder delete don't work so well (some give warnings, other don't delete hidden files etc).

this one is working fine:
<?php

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

?>
2015-05-26 20:07:32
http://php5.kiev.ua/manual/ru/function.rmdir.html
Never ever use jurchiks101 at gmail dot com code!!! It contains command injection vulnerability!!!
If you want to do it that way, use something like this instead:

<?php
if (PHP_OS === 'Windows')
{
   
exec(sprintf("rd /s /q %s"escapeshellarg($path)));
}
else
{
   
exec(sprintf("rm -rf %s"escapeshellarg($path)));
}
?>

Note the escapeshellarg usage to escape any possible unwanted character, this avoids putting commands in $path variable so the possibility of someone "pwning" the server with this code
2016-02-11 11:16:46
http://php5.kiev.ua/manual/ru/function.rmdir.html
Автор:
itay at itgoldman's function falls into an infinite loop if the $src directory doesn't exist.
Here's a fix - one should do at least a file_exists() check before the loop:

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

Thanks to itay for the original function, though, it was helpful.
2016-09-26 01:44:52
http://php5.kiev.ua/manual/ru/function.rmdir.html
it Will Delete All Fildes in folder and that folder too...

echo $path = 'D:\xampp\htdocs\New folder\New folder';

function rmdir_recursive($dir) {
    $it = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
    $it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
    foreach($it as $file) {
        if ($file->isDir()) rmdir($file->getPathname());
        else unlink($file->getPathname());
    }
    rmdir($dir);
}
rmdir_recursive($path);
2019-03-08 10:19:03
http://php5.kiev.ua/manual/ru/function.rmdir.html
Автор:
// Recursive PHP function to completely remove a directory

function delete_directory_recursively( $path ) {

      $dir = new \DirectoryIterator( $path );

      // Iterate through the subdirectories / files of the provided directory
      foreach ( $dir as $dir_info ) {

        // Exclude the . (current directory) and .. (parent directory) paths
        // from the directory iteration
        if ( ! $dir_info->isDot() ) {

          // Get the full currently iterated path
          $iterated_path = $dir_info->getPathname();

          // If the currently iterated path is a directory
          if ( $dir_info->isDir() ) {

            // which is not empty (in which case scandir returns an array of not 2 (. and ..) elements)
            if ( count( scandir( $iterated_path ) ) !== 2 ) {

              // Call the function recursively
              self::remove_directory_recursively( $iterated_path );

            } else {

              // if the currently iterated path is an empty directory, remove it
              rmdir( $iterated_path );

            }

          } elseif ( $dir_info->isFile() ) {

            // If the currently iterated path describes a file, we need to
            // delete that file
            unlink( $iterated_path );

          }

        } // loop which opens if the currently iterated directory is neither . nor ..

      } // end of iteration through directories / files of provided path

      // After iterating through the subpaths of the provided path, remove the
      // concerned path
      rmdir( $path );

    } // end of delete_directory_recursively() function definition
2021-02-12 16:48:25
http://php5.kiev.ua/manual/ru/function.rmdir.html
a simple snipped for removing empty dirs recursive :

<?php
function removeEmptyDirs($fullPath)
    {
        if(!
is_dir($fullPath)){
            return;
        }

       
$children array_diff(scandir($fullPath), ['.','..']);

        foreach(
$children as $child){
           
removeEmptyDirs($fullPath$childDIRECTORY_SEPARATOR);
        }

       
$children array_diff(scandir($fullPath), ['.','..']);
        if(empty(
$children)){
            echo 
"the $fullPath empty directory has been removed.\n";
           
rmdir($fullPath);
        }
    }
?>
2022-08-31 15:23:20
http://php5.kiev.ua/manual/ru/function.rmdir.html

    Поддержать сайт на родительском проекте КГБ