百科狗-知识改变命运!
--

rmdir() - 删除目录 - php 文件目录函数

梵高1年前 (2023-11-21)阅读数 24#技术干货
文章标签目录

rmdir()

(PHP 4, PHP 5, PHP 7)

删除目录

说明

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

尝试删除$dirname所指定的目录。该目录必须是空的,而且要有相应的权限。失败时会产生一个E_WARNING级别的错误。

参数

$dirname

目录的路径。

$context

Note:在 PHP 5.0.0中增加了对上下文(Context)的支持。有关上下文(Context)的说明参见Streams。

返回值

成功时返回TRUE,或者在失败时返回FALSE

更新日志

版本说明
5.0.0自 PHP 5.0.0 起rmdir()也可用于某些URL 封装协议。参见支持的协议和封装协议的列表看看rmdir()支持哪些 URL 封装协议。

范例

Example #1rmdir()例子

注释

rmdir() - 删除目录 - php 文件目录函数

Note:当启用安全模式时,PHP 会在执行脚本时检查被脚本操作的目录是否与被执行的脚本有相同的 UID(所有者)。

参见

  • is_dir() 判断给定文件名是否是一个目录
  • mkdir() 新建目录
  • unlink() 删除文件
Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree. 
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: 
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...
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:

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
Another simple way to recursively delete a directory that is not empty: 
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.
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

may solve the problem!
Make sure to write this before rmdir($dirname);.
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! 
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.
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.
It is rather dangerous to recurse into symbolically linked directories. The delTree should be modified to check for links. 
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) ;
  }
  
}
//This is one example to delete full directory with all files inside there
function delDir($path){
    if(is_dir($path) == TRUE){
      $rootFolder = scandir($path);
      if(sizeof($rootFolder) > 2){
        foreach($rootFolder as $folder){
          if($folder != "." && $folder != ".."){
//Pass the subfolder to function
            delDir($path."/".$folder);
          }
        }
//On the end of foreach the directory will be cleaned, and you will can use rmdir, to remove it
        rmdir($path);
      }
    }else{
      if(file_exists($path) == TRUE){
        unlink($path);
      }
    }
  }
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
A patch to previous script to make sure rights for deletion is set:

[EDITOR NOTE: "Credits to erkethan at free dot fr." - thiago]
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().
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. 
I wasn't having much luck with the recursive delete functions below, so I wrote my own:

Simple. Works.
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?
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
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.
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'.
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);
Concise way to recursively remove a directory: 
This version delete tree 
if you get this problem Permission denied in windows testing your site maybe this will resolve the problem 

and then 
I had situation where the rmdir was returning warning message as within last loop it was already removed. So here is quick fix by adding is_dir to the DelTree routine below 
This function sorely needs a built-in option to delete the contents of the directory. Or another function that does exactly that - deletes a path (file or folder, doesn't matter).
It is still much simpler to just use something like the following to delete any directory rather than write some 10+ line function that has corner cases that will break it:

Most webservers are run on 2 or 3 different popular operating systems, so this would easily work for almost all websites.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)