PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

set_file_buffer> <rewind
Last updated: Fri, 05 Sep 2008

view this page in

rmdir

(PHP 4, PHP 5)

rmdirディレクトリを削除する

説明

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

dirname で指定されたディレクトリを 削除しようと試みます。ディレクトリは空でなくてはならず、また 適切なパーミッションが設定されていなければなりません。

パラメータ

dirname

ディレクトリへのパス。

context

注意: コンテキストのサポートは、 PHP 5.0.0 で追加されました。contexts の説明に関しては、 ストリーム 関数 を参照してください。

返り値

成功した場合に TRUE を、失敗した場合に FALSE を返します。

変更履歴

バージョン 説明
5.0.0 PHP 5.0.0 以降、rmdir()いくつかの URL ラッパーを併用することが可能です。 rmdir() をサポートしているラッパーの一覧については、 サポートされるプロトコル/ラッパー を参照ください。

注意

注意: セーフモード が有効の場合、PHP は、 操作を行うディレクトリが、実行するスクリプトと同じ UID (所有者)を有しているか どうかを確認します。

参考



set_file_buffer> <rewind
Last updated: Fri, 05 Sep 2008
 
add a note add a note User Contributed Notes
rmdir
TrashF at taistelumarsu dot org
08-Aug-2008 12:21
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().
kisgabo94 at freemail dot hu
11-Jul-2008 12:06
A function that deletes a dir that not empty:
Returns true on success, or false on faileure.

function advancedRmdir($path) { //mappát töröl akkor is, ha nem üres
    $origipath = $path;
    $handler = opendir($path);
    while (true) {
        $item = readdir($handler);
        if ($item == "." or $item == "..") {
            continue;
        } elseif (gettype($item) == "boolean") {
            closedir($handler);
            if (!@rmdir($path)) {
                return false;
            }
            if ($path == $origipath) {
                break;
            }
            $path = substr($path, 0, strrpos($path, "/"));
            $handler = opendir($path);
        } elseif (is_dir($path."/".$item)) {
            closedir($handler);
            $path = $path."/".$item;
            $handler = opendir($path);
        } else {
            unlink($path."/".$item);
        }
    }
    return true;
}
hoffmeister
02-Jun-2008 07:17
A simple method
<?php
$path
="./folder/folder_to_delete/";

$handle = opendir($path)

for (;
false !== ($file = readdir($handle));) if($file != "." && $file != "..") unlink($path.$file);
closedir($handle);
rmdir($section);

?>

or with error checking
<?php
$path
="./folder/folder_to_delete/";
if (
$handle = opendir($path))
{
    for (;
false !== ($file = readdir($handle));)
    {
        if(
$file != "." && $file != "..")
        {
            if(
unlink($path.$file)) $info.="file ".$file." delete sussfully<BR>";
            else
$info.="Unable to delete file ".$file."<BR>";
        }
    }
   
closedir($handle);
    if(!
rmdir($section)) $info.="<BR>Could not delete directory ".$path;
    else
$info.='<BR>'.$path.' deleted';
}
else
$info.="problrm deleting directory";
?>
ornthalas at NOSPAM dot gmail dot com
11-May-2008 10:25
I don't know why, but the glob() function seems to take some time to release file handles.

The consequence is some annoying permission denied on random files.

Using opendir() instead of glob() fixes the problem.

<?php
function rm_recursive($filepath)
{
    if (
is_dir($filepath) && !is_link($filepath))
    {
        if (
$dh = opendir($filepath))
        {
            while ((
$sf = readdir($dh)) !== false)
            {
                if (
$sf == '.' || $sf == '..')
                {
                    continue;
                }
                if (!
rm_recursive($filepath.'/'.$sf))
                {
                    throw new
Exception($filepath.'/'.$sf.' could not be deleted.');
                }
            }
           
closedir($dh);
        }
        return
rmdir($filepath);
    }
    return
unlink($filepath);
}
?>

Please note that opendir() method is faster than the glob() method.
Isaac Z dot Schlueter i at foohack dot com
24-Apr-2008 10:25
This function builds on the suggestion by davedx, but doesn't keep going on failure.  It also doesn't remove dot-files, since those usually should be deleted explicitly.

<?php
/**
 * rm_recurse
 * @description Remove recursively. (Like `rm -r`)
 * @see Comment by davedx at gmail dot com on { http://us2.php.net/manual/en/function.rmdir.php }
 * @param file {String} The file or folder to be deleted.
 **/
function rm_recurse($file) {
    if (
is_dir($file) && !is_link($file)) {
        foreach(
glob($file.'/*') as $sf) {
            if ( !
rm_recurse($sf) ) {
               
error_log("Failed to remove $sf\n");
                return
false;
            }
        }
        return
rmdir($file);
    } else {
        return
unlink($file);
    }
}
?>
davedx at gmail dot com
01-Apr-2008 12:19
Or even just

function deltree($f) {
  if (is_dir($f)) {
    foreach(glob($f.'/*') as $sf) {
      if (is_dir($sf) && !is_link($sf)) {
        deltree($sf);
      } else {
        unlink($sf);
      } 
    } 
  }
  rmdir($f);
}

...As we're already calling rmdir($f) at the end of deltree.
rjcarr at gmail dot com
23-Mar-2008 08:08
To the poster on 03-Mar-2008 05:33, if the directory contains more than one file, your rmdir($f) will (silently) warn that the dir isn't empty. 

I think the following, although not quite as elegant, fixes the problem. 

<?php
function deltree($f) {
  if (
is_dir($f)) {
    foreach(
glob($f.'/*') as $sf) {
      if (
is_dir($sf) && !is_link($sf)) {
       
deltree($sf);
       
rmdir($sf);
         
      } else {
       
unlink($sf);
      }  
    }  
  }

 
rmdir($f);
}
?>
LiTuS
16-Mar-2008 01:33
This is another deltree function version from  boccheciampe (and lukas and first one from vboedefeld)

Notice that I put the rmdir sentence out of the foreach loop. In the boccheciampe version the rmdir was in the foreach loop and I think that it's an error because it tries to delete the same directory on every loop.

And this version propagates the result of the operation for a better control of it.

function esborrar_directori($ruta)
{
     if (!empty($ruta) && $ruta != '.' && $ruta != '..' )
     {
          if (is_dir($ruta))
          {
                foreach(glob($ruta.'/*') as $node)
                {
                    if (is_dir($node) && !is_link($node))
                        $swOK = ($node == '.' || $node == '..' || esborrar_directori($node));
                    else
                        $swOK = unlink($node);
               
                    if (!$swOK)    return false;
                 }
           
                 return rmdir($ruta);
           }    
      }
   
      return false;
}
dan
10-Mar-2008 10:25
I use the following to delete a folder and all its content, and it works fine without being forced to upgrade to PHP5:   

function remove_dir($dir)
    {
        if(is_dir($dir))
        {
            $dir = (substr($dir, -1) != "/")? $dir."/":$dir;
            $openDir = opendir($dir);
            while($file = readdir($openDir))
            {
                if(!in_array($file, array(".", "..")))
                {
                    if(!is_dir($dir.$file))
                        @unlink($dir.$file);
                    else
                        remove_dir($dir.$file);
                }
            }
            closedir($openDir);
            @rmdir($dir);
        }
    }
boccheciampe at dpt-info.u-strasbg.fr
03-Mar-2008 01:33
About the improved deltree function from lukas at example dot com (and first one from vboedefeld at googlemail dot com) :

I'm not sure but it looks like the function doesn't delete the very first directory :

# mkdir -p /tmp/foo/{test1,test2}
# php deltree.php /tmp/foo
# ls -l /tmp/foo/
total 0

My directory "foo" is still there. Unless it is what you really want the function to do, I think the "rmdir($sf)" is at the wrong place.

The new improved function is :

<?php

function deltree($f) {
    if (
is_dir($f)) {
        foreach(
glob($f.'/*') as $sf) {
            if (
is_dir($sf) && !is_link($sf)) {
               
deltree($sf);
               
// rmdir($sf); <== old place with arg "$sf"
           
} else {
               
unlink($sf);
            }

           
rmdir($f); // <== new place with new arg "$f"
       
}
    } else {
        die(
"Error: not a directory - $f");
    }
}

?>

Let me know if I'm wrong :)

@+
anonymous
22-Feb-2008 02:19
WARNING: the code posted by Anonymous on Feb 15 2008 contains a serious typo that will delete everything in the hierarchy of the deleted path. The line
<?php
        
if ( (!strcmp($item, '.')) OR (!strcmp($item, '..')) ) continue; // WRONG!
?>
should be
<?php
        
if ( (!strcmp($item, '.')) AND (!strcmp($item, '..')) ) continue; // correct
?>
lukas at example dot com
16-Feb-2008 07:13
I've improved the function of vboedefeld at googlemail dot com:

The function worked fine but I had a typo in the variable name I passed to the function, and as a result I have lost all files (I've had a backup)

So I made the function check first if the passed path is a directory:

<?php

function deltree($f) {
    if (
is_dir($f)) {
        foreach(
glob($f.'/*') as $sf) {
            if (
is_dir($sf) && !is_link($sf)) {
               
deltree($sf);
               
rmdir($sf);
            } else {
               
unlink($sf);
            }
        }
    } else {
        die(
"Error: not a directory - $f");
    }
}

?>
Anonymous
15-Feb-2008 07:39
in case someone is still stuck on PHP4 server, you need to use this improvised function instead of "scandir" PHP5 built-in function:

function scanEntireDir($dir)
{
    $dh  = opendir($dir);
   
    while (false !== ($filename = readdir($dh))) {
        $files[] = $filename;
    }
   
    closedir($dh);
   
    return $files;
}

so this would work quite fine:

function delTree($f)
    {
        if (is_dir($f)) {
            foreach($this->scanEntireDir($f) as $item){
                if ( (!strcmp($item, '.')) OR (!strcmp($item, '..')) ) continue;
                delTree($f . "/" . $item); // recurision
            }
            rmdir($f);
        }
        else{
            unlink($f);
        }
       
        // check if deleted?
        if (is_dir($f)) return false;
        else return true;
    }

cheers!
vboedefeld at googlemail dot com
10-Feb-2008 02:25
Another sugestion (even a little shorter):

<?php
 
function deltree($f){
    foreach(
glob($f.'/*') as $sf){
      if (
is_dir($sf) && !is_link($sf)){
       
deltree($sf);
       
rmdir($sf);
      }else{
       
unlink($sf);
      }
    }
  }
?>
anders dot carlsson at dwm dot se
11-Jan-2008 09:09
All of you who proposed routines for recursive deletion of a directory tree, I have one suggestion:

if (is_dir($f) && !is_link($f)) { ... }

Otherwise, if you happen to have a symbolic link to a directory outside of the one you plan to remove and also have permissions enough to wipe that too, nasty things could happen. It just happened to me, and I had to retrieve lost files from the backup. :-/
fabiovaz at gmail dot com
10-Jan-2008 07:20
function deltree( $f ){
        if( is_dir( $f ) ){
            foreach( scandir( $f ) as $item ){
                if( !strcmp( $item, '.' ) || !strcmp( $item, '..' ) )
                    continue;
                $this->deltree( $f . "/" . $item );
            }
            rmdir( $f );
        } else {
            unlink( $f );
        }
    }
rn at clubfl dot com
18-Dec-2007 07:16
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.
saeven at saeven dot net
29-Nov-2007 08:52
Improved example:

function deltree( $f ){

    if( is_dir( $f ) ){
        foreach( scandir( $f ) as $item ){
            if( !strcmp( $item, '.' ) || !strcmp( $item, '..' ) )
                continue;       
            deltree( $f . "/" . $item );
        }   
        rmdir( $f );
    }
    else{
        unlink( $f );
    }
}
Cheetah Designs
23-Oct-2007 04:19
None of the below functions worked for me, so I created this function to delete a folder, deleting anything in it first:

function RecursiveFolderDelete ( $folderPath )
{
    if ( is_dir ( $folderPath ) )
    {
        foreach ( scandir ( $folderPath )  as $value )
        {
            if ( $value != "." && $value != ".." )
            {
                $value = $folderPath . "/" . $value;

                if ( is_dir ( $value ) )
                {
                    FolderDelete ( $value );
                }
                elseif ( is_file ( $value ) )
                {
                    @unlink ( $value );
                }
            }
        }

        return rmdir ( $folderPath );
    }
    else
    {
        return FALSE;
    }
}
contacts [from] nexus-soft [dot] org
19-Oct-2007 04:08
The PHP4 version below can not delete subfolders, just files. Here is a complete PHP4/5 recursive folder/subfolder delete function:

<?php

function deltree($path) {
  if (
is_dir($path)) {
      if (
version_compare(PHP_VERSION, '5.0.0') < 0) {
       
$entries = array();
      if (
$handle = opendir($path)) {
        while (
false !== ($file = readdir($handle))) $entries[] = $file;

       
closedir($handle);
      }
      } else {
       
$entries = scandir($path);
        if (
$entries === false) $entries = array(); // just in case scandir fail...
     
}

    foreach (
$entries as $entry) {
      if (
$entry != '.' && $entry != '..') {
       
deltree($path.'/'.$entry);
      }
    }

    return
rmdir($path);
  } else {
      return
unlink($path);
  }
}

?>

Thanks to the two codes below for the jump start on this one.
webmaster at gprodesign dot com
13-Oct-2007 03:38
For those still using PHP 4, here is an alternative to the last post:

<?php

function deltree($path) {
  if (
is_dir($path)) {
    if (
$handle = opendir($path)) {
      while (
false !== ($file = readdir($handle))) {
        if (
$file != '.' && $file != '..') {
         
unlink($path."/".$file);
          }
        }
     
closedir($handle);
     
rmdir($path);
      return
1;
      }
    }
  return;
  }

?>
lior at realdice dot com
08-Oct-2007 06:55
This will delete a directory and its' contents.
Set DIRECTORY_SEPARATOR to whatever fits the target OS.

function deltree($path) {
  if (is_dir($path)) {
    $entries = scandir($path);
    foreach ($entries as $entry) {
      if ($entry != '.' && $entry != '..') {
        deltree($path.DIRECTORY_SEPARATOR.$entry);
      }
    }
    rmdir($path);
  } else {
    unlink($path);
  }
}
bhuvidya at yahoo dot com dot au
07-Oct-2007 02:50
dear bluej100:

i think there's a bug in the line:

if ($child[0] == '.') {continue;}

it is possible to have a directory that starts with '.', eg '.tmpfiles' - i think the above line is just trying to catch '.' and '..', so you will have to do the following:

if ($child == '.' || $child == '..')
{
   continue;
}
bluej100@gmail
31-Aug-2007 02:21
Here's my stack-based pseudo-recursive rmdir. It borrows heavily from andy at mentalist's.

<?php
function rmdir_r($path) {
  if (!
is_dir($path)) {return false;}
 
$stack = Array($path);
  while (
$dir = array_pop($stack)) {
    if (@
rmdir($dir)) {continue;}
   
$stack[] = $dir;
   
$dh = opendir($dir);
    while ((
$child = readdir($dh)) !== false) {
      if (
$child[0] == '.') {continue;}
     
$child = $dir . DIRECTORY_SEPARATOR . $child;
      if (
is_dir($child)) {$stack[] = $child;}
      else {
unlink($child);}
    }
  }
  return
true;
}
?>
swizec at swizec dot com
31-Jul-2007 03:53
Here is a better recursive rmdir function, that relies on php's built-in dir class and doesn't use messy directory changing.

<?php
   
function full_rmdir( $dir )
    {
        if ( !
is_writable( $dir ) )
        {
            if ( !@
chmod( $dir, 0777 ) )
            {
                return
FALSE;
            }
        }
       
       
$d = dir( $dir );
        while (
FALSE !== ( $entry = $d->read() ) )
        {
            if (
$entry == '.' || $entry == '..' )
            {
                continue;
            }
           
$entry = $dir . '/' . $entry;
            if (
is_dir( $entry ) )
            {
                if ( !
$this->full_rmdir( $entry ) )
                {
                    return
FALSE;
                }
                continue;
            }
            if ( !@
unlink( $entry ) )
            {
               
$d->close();
                return
FALSE;
            }
        }
       
       
$d->close();
       
       
rmdir( $dir );
       
        return
TRUE;
    }
?>
NuK
27-Jun-2007 08:24
One more note to babca's improvement (of function from "brousky - gmail"):

just do the readdir() like in the Example 498 http://es.php.net/manual/en/function.readdir.php

<?php
# ......

while(false!==($file=readdir($dirHandle)))

# ......
?>
ljubiccica at yahoo dot com
12-Jun-2007 07:06
Note to babca's improvement (of function from "brousky - gmail"):

I think you forgot to call your function with a new name?
(if (!rmdir_rf($file)) return false; -> if (!full_rmdir($file)) return false;)

<?
function full_rmdir($dirname){
        if (
$dirHandle = opendir($dirname)){
           
$old_cwd = getcwd();
           
chdir($dirname);

            while (
$file = readdir($dirHandle)){
                if (
$file == '.' || $file == '..') continue;

                if (
is_dir($file)){
                    if (!
full_rmdir($file)) return false;
                }else{
                    if (!
unlink($file)) return false;
                }
            }

           
closedir($dirHandle);
           
chdir($old_cwd);
            if (!
rmdir($dirname)) return false;

            return
true;
        }else{
            return
false;
        }
    }
?>
   
Nice function thou...
=)
babca (plutanium.cz)
07-Jun-2007 01:22
Improvement of function from "brousky - gmail":

-Removes a directory and everything in it
-After calling this function the current working directory (cwd) of the script won't be changed
-Function returns true/false

<?php
function full_rmdir($dirname)
    {
    if (
$dirHandle = opendir($dirname))
        {
       
$old_cwd = getcwd();
       
chdir($dirname);
       
        while (
$file = readdir($dirHandle))
            {
            if (
$file == '.' || $file == '..') continue;
           
            if (
is_dir($file))
                {
                if (!
rmdir_rf($file)) return false;
                }
            else
                {
                if (!
unlink($file)) return false;
                }
            }
       
       
closedir($dirHandle);
       
chdir($old_cwd);
        if (!
rmdir($dirname)) return false;
       
        return
true;
        }
    else
        {
        return
false;
        }
    }
?>

Enjoy :)
brousky - gmail
01-Jun-2007 12:14
equivalent of :
rmdir -rf

ie. remove a directory and everything that's in it. Note that after calling this function the current working directory of the script will be the parent of the directory you deleted.

<?php

function rmdir_rf($dirname) {
    if (
$dirHandle = opendir($dirname)) {
       
chdir($dirname);
        while (
$file = readdir($dirHandle)) {
            if (
$file == '.' || $file == '..') continue;
            if (
is_dir($file)) rmdir_rf($file);
            else
unlink($file);
        }
       
chdir('..');
       
rmdir($dirname);
       
closedir($dirHandle);
    }
}

?>
jeremiah (at) jkjonesco (dot) com
17-May-2007 07:54
Here is a very clean, readable (hopefully) recursive way to delete everything in a directory.  This also handles deleteing links to ensure a non-recursive follow through a symlink and just deletes the link instead.  It is in the form of a class so that you can plug it right into your existing classes or libraries.

Here is how to use the recursive delete (unlink) function:

<?php
$path
= '/absolute/path/to/some/file/filename.ext';
if(!
FileFunctions::unlink($path)) echo "One or more files could not be deleted";
?>

Here is the class:

<?php
/**
 * Provides file functionality that extends the built-in PHP functions
 *
 * @author jjones
 *
 */
class FileFunctions
{
   
/**
     * Recursive unlink function
     *
     * This will delete the provided path.  If the path is a
     * directory, it will delete the directory.  It will
     * recursively delete any subdirectories/files.
     *
     * @param String $path Path to file/directory to recursively unlink
     */
   
public function unlink($path)
    {
       
/*    make sure the path exists    */
       
if(!file_exists($path)) return false;
       
       
/*    If it is a file or link, just delete it    */
       
if(is_file($path) || is_link($path)) return @unlink($path);
       
       
/*    Scan the dir and recursively unlink    */
       
$files = scandir($path);
        foreach(
$files as $filename)
        {
            if(
$filename == '.' || $filename == '..') continue;
           
$file = str_replace('//','/',$path.'/'.$filename);
           
self::unlink($file);
        }
//end foreach
       
        /*    Remove the parent dir    */
       
if(!@rmdir($path)) return false;
        return
true;
    }
//end function unlink
}//end class FileFunctions
?>
eli dot hen at gmail dot com
25-Jan-2007 04:54
This functions deletes or empties the directory.
Without using recursive functions!

<?php

/**
 * Removes the directory and all its contents.
 *
 * @param string the directory name to remove
 * @param boolean whether to just empty the given directory, without deleting the given directory.
 * @return boolean True/False whether the directory was deleted.
 */
function deleteDirectory($dirname,$only_empty=false) {
    if (!
is_dir($dirname))
        return
false;
   
$dscan = array(realpath($dirname));
   
$darr = array();
    while (!empty(
$dscan)) {
       
$dcur = array_pop($dscan);
       
$darr[] = $dcur;
        if (
$d=opendir($dcur)) {
            while (
$f=readdir($d)) {
                if (
$f=='.' || $f=='..')
                    continue;
               
$f=$dcur.'/'.$f;
                if (
is_dir($f))
                   
$dscan[] = $f;
                else
                   
unlink($f);
            }
           
closedir($d);
        }
    }
   
$i_until = ($only_empty)? 1 : 0;
    for (
$i=count($darr)-1; $i>=$i_until; $i--) {
        echo
"\nDeleting '".$darr[$i]."' ... ";
        if (
rmdir($darr[$i]))
            echo
"ok";
        else
            echo
"FAIL";
    }
    return ((
$only_empty)? (count(scandir)<=2) : (!is_dir($dirname)));
}

?>
PHPcoder at cyberpimp dot sexventure dot com
18-Jan-2007 06:42
This is my solution for removing directories:

<?php
/* Function to remove directories, even if they contain files or
subdirectories.  Returns array of removed/deleted items, or false if nothing
was removed/deleted.

by Justin Frim.  2007-01-18

Feel free to use this in your own code.
*/

function rmdirtree($dirname) {
    if (
is_dir($dirname)) {    //Operate on dirs only
       
$result=array();
        if (
substr($dirname,-1)!='/') {$dirname.='/';}    //Append slash if necessary
       
$handle = opendir($dirname);
        while (
false !== ($file = readdir($handle))) {
            if (
$file!='.' && $file!= '..') {    //Ignore . and ..
               
$path = $dirname.$file;
                if (
is_dir($path)) {    //Recurse if subdir, Delete if file
                   
$result=array_merge($result,rmdirtree($path));
                }else{
                   
unlink($path);
                   
$result[].=$path;
                }
            }
        }
       
closedir($handle);
       
rmdir($dirname);    //Remove dir
       
$result[].=$dirname;
        return
$result;    //Return array of deleted items
   
}else{
        return
false;    //Return false if attempting to operate on a file
   
}
}
?>
05-Jan-2007 02:10
This code won`t work if you have subdirectories with new subdirecories.

Add this:
if(!@rmdir($subDir)) //@ suppress the warning message
{
   recursiveRemoveDirectory($subDir);
   rmdir($subDir);
}

.. or it wont delete your sub-subdirectories. Took me quite some time to figure out this..
fkjaekel at yahoo dot com dot br
07-Nov-2006 07:32
Using SPL:

<?php
   
function recursiveRemoveDirectory($path)
    {   
       
$dir = new RecursiveDirectoryIterator($path);

       
//Remove all files
       
foreach(new RecursiveIteratorIterator($dir) as $file)
        {
           
unlink($file);
        }

       
//Remove all subdirectories
       
foreach($dir as $subDir)
        {
           
//If a subdirectory can't be removed, it's because it has subdirectories, so recursiveRemoveDirectory is called again passing the subdirectory as path
           
if(!@rmdir($subDir)) //@ suppress the warning message
           
{
               
recursiveRemoveDirectory($subDir);
            }
        }

       
//Remove main directory
       
rmdir($path);
    }
?>
sarangan dot thuraisingham at gmail dot com
03-Nov-2006 09:52
I installed Joomla CMS and the files where under apache user. So I couldn't delete from my SSH login. Your little function helped. But, you forgot about hidden files in Unix. Filenames beginning with a . are not returned in the glob list. So the modified code looks like this:

<?php
function removeDir($path) {
  
// Add trailing slash to $path if one is not there
  
if (substr($path, -1, 1) != "/") {
      
$path .= "/";
   }

  
$normal_files = glob($path . "*");
  
$hidden_files = glob($path . "\.?*");
  
$all_files = array_merge($normal_files, $hidden_files);

   foreach (
$all_files as $file) {
       
# Skip pseudo links to current and parent dirs (./ and ../).
       
if (preg_match("/(\.|\.\.)$/", $file))
        {
                continue;
        }

       if (
is_file($file) === TRUE) {
          
// Remove each file in this Directory
          
unlink($file);
           echo
"Removed File: " . $file . "<br>";
       }
       else if (
is_dir($file) === TRUE) {
          
// If this Directory contains a Subdirectory, run this Function on it
          
removeDir($file);
       }
   }
  
// Remove Directory once Files have been removed (If Exists)
  
if (is_dir($path) === TRUE) {
      
rmdir($path);
       echo
"<br>Removed Directory: " . $path . "<br><br>";
   }
}

#To remove a dir:
removeDir('/home/fhlinux206/t/thuraisingham.net/tmp/');
?>
FormatThis
19-Oct-2006 05:47
@ null at php5 dot pl & stijnleenknegt< at >gmail< dot >com & mediengestalter at gleichjetzt dot de:
[EDITORS NOTE: Mentioned Notes have all been Removed (Previous Examples)]

I believe the following is what you were trying to make happen.  notes and echo commands have been added so you can see what is being done as it happens and also threw in the actual rmdir function so that the directories as well will be removed and not just the files.

<?php
function removeDir($path) {
   
// Add trailing slash to $path if one is not there
   
if (substr($path, -1, 1) != "/") {
       
$path .= "/";
    }
    foreach (
glob($path . "*") as $file) {
        if (
is_file($file) === TRUE) {
           
// Remove each file in this Directory
           
unlink($file);
            echo
"Removed File: " . $file . "<br>";
        }
        else if (
is_dir($file) === TRUE) {
           
// If this Directory contains a Subdirectory, run this Function on it
           
removeDir($file);
        }
    }
   
// Remove Directory once Files have been removed (If Exists)
   
if (is_dir($path) === TRUE) {
       
rmdir($path);
        echo
"<br>Removed Directory: " . $path . "<br><br>";
    }
}
?>
les_diadoques at worldonline dot fr
06-Jun-2006 10:00
For PHP 3-4-5.
No trailing "/" at the end of the path.

<?php

function remove_directory($dir) {
  if (
$handle = opendir("$dir")) {
    while (
false !== ($item = readdir($handle))) {
      if (
$item != "." && $item != "..") {
        if (
is_dir("$dir/$item")) {
         
remove_directory("$dir/$item");
        } else {
         
unlink("$dir/$item");
          echo
" removing $dir/$item<br>\n";
        }
      }
    }
   
closedir($handle);
   
rmdir($dir);
    echo
"removing $dir<br>\n";
  }
}

remove_directory("/path/to/dir");

?>
brianleeholub at yahoo dot com
12-May-2006 08:30
this will only work in php5 (scandir).

feed this function the path to a directory (INCLUDE TRAILING /) and it'll clean it of all contents (if it contains a directory with more stuff it'll dive down and clean that out). use with care!

remove_directory('/path/to/crap/for/deletion/');

function remove_directory($dir) {
        $dir_contents = scandir($dir);
        foreach ($dir_contents as $item) {
            if (is_dir($dir.$item) && $item != '.' && $item != '..') {
                remove_directory($dir.$item.'/');
            }
            elseif (file_exists($dir.$item) && $item != '.' && $item != '..') {
                unlink($dir.$item);
            }
        }
        rmdir($dir);
    }
not at any dot com
14-Apr-2006 08:21
Save some time, if you want to clean a directory or delete it and you're on windows.

Use This:

            chdir ($file_system_path);
            exec ("del *.* /s /q");

You can use other DEL syntax, or any other shell util.
You may have to allow the service to interact with the desktop, as that's my current setting and I'm not changing it to test this.
dao at design-noir.de
19-Feb-2006 12:17
[bobbfwed at comcast dot net], you posted really bad code. The constant and the global variable are absolutely useless and make the function inflexible and fault-prone. Furthermore your error echo'ing is weird, you should use trigger_error().

Now, since previous rmdirr() implementations lack the ability to simply clear a directory and ClearDirectory() / RemoveDirectory() by [mn dot yarar at gmail dot com] didn't work with nested directories, I've rewritten them: http://en.design-noir.de/webdev/PHP/rmdirr_cleardir/
bobbfwed at comcast dot net
02-Feb-2006 08:20
I have programmed a really nice program that remotely lets you manage files as if you have direct access to them (http://sourceforge.net/projects/filemanage/). I have a bunch of really handy functions to do just about anything to files or directories. In it I use this directory delete function.
Here is the function I made; it will likely need tweaking to work as a standalone script, since it relies of variables set by my program (eg: loc1 -- which dynamically changes in my program):

<?PHP

 
// loc1 is the path on the computer to the base directory that may be moved
define('loc1', 'C:/Program Files/Apache Group/Apache/htdocs', true);

 
// use this format:
$dir = '[reletive path]';
if(
remdir($dir))
 
rmdir($dir);
else
  echo
'There was an error.';

 
// this function deletes all files and sub directories directories in a directory
  // bool remdir( str 'directory path' )
function remdir($dir){

  if(!isset(
$GLOBALS['remerror']))
   
$GLOBALS['remerror'] = false;

  if(
$handle = opendir(loc1 . $dir)){           // if the folder exploration is sucsessful, continue
   
while (false !== ($file = readdir($handle))){ // as long as storing the next file to $file is successful, continue
     
$path = $dir . '/' . $file;
      if(
is_file(loc1 . $path)){
        if(!
unlink(loc1 . $path)){
          echo
'<u><font color="red">"' . $path . '" could not be deleted. This may be due to a permissions problem.</u><br>Directory cannot be deleted until all files are deleted.</font><br>';
         
$GLOBALS['remerror'] = true;
          return
false;
        }
      } else
      if(
is_dir(loc1 . $path) && substr($file, 0, 1) != '.'){
       
remdir($path);
        @
rmdir(loc1 . $path);
      }
    }
   
closedir($handle); // close the folder exploration
 
}

  if(!
$GLOBALS['remerror']) // if no errors occured, delete the now empty directory.
   
if(!rmdir(loc1 . $dir)){
      echo
'<b><font color="red">Could not remove directory "' . $dir . '". This may be due to a permissions problem.</font></b><br>';
      return
false;
    } else
      return
true;

  return
false;
}
// end of remdir()
?>

This new function will be in 0.9.7 (the current release of File Manage) which was just released.
Hope this helps some people.
mn dot yarar at gmail dot com
02-Feb-2006 11:36
/***********************************
Author : M. Niyazi Yarar
Created : February, 2006
Description : Simply clean files
and removes the directory

If any error occurs or for your suggestions,
please send me e-mail
***********************************/
function ClearDirectory($path){
    if($dir_handle = opendir($path)){   
        while($file = readdir($dir_handle)){   
            if($file == "." || $file == ".."){
                if(!@unlink($path."/".$file)){
                    continue;
                }               
            }else{
                @unlink($path."/".$file);
            }
        }
        closedir($dir_handle);
        return true;
// all files deleted
    }else{
        return false;
// directory doesnt exist
    }   
}
function RemoveDirectory($path){
    if(ClearDirectory($path)){
        if(rmdir($path)){
            return true;
// directory removed
        }else{
            return false;
// directory couldnt removed
        }
    }else{
        return false;
// no empty directory
    }
}
/***************************************
Example Usage

if(RemoveDirectory("/mysite/images")){
    echo 'Uughh! All images gone!';
}else{
    echo 'Ohh, well done. I am so lucky';
}
***************************************/
Andreas Kalsch (akidee.de)
02-Jan-2006 08:43
a function that deletes a directory - beginning with the deepest directory and its files.

- it really works if you have enough rights.
- it returns a boolean value if everything is properly done.

function deleteDir($dir)
{
    if (substr($dir, strlen($dir)-1, 1) != '/')
        $dir .= '/';

    echo $dir;

    if ($handle = opendir($dir))
    {
        while ($obj = readdir($handle))
        {
            if ($obj != '.' && $obj != '..')
            {
                if (is_dir($dir.$obj))
                {
                    if (!deleteDir($dir.$obj))
                        return false;
                }
                elseif (is_file($dir.$obj))
                {<