Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Filesystem Functions : rmdir

rmdir

Removes directory (PHP 4, PHP 5)
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.

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 Appendix O, List of Supported Protocols/Wrappers for a listing of which wrappers support rmdir().

Notes

Note:

When safe mode is enabled, PHP checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.

See Also
mkdir()
unlink()

Related Examples ( Source code ) » rmdir




Code Examples / Notes » rmdir

dao

[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/


itsdapead

Warning!  On Unix-type systems, most of the "delete directory tree" functions posted here will follow & delete symbolic links (which is not what you'd expect of, say, rm-rf) so you might find more than you bargained for getting wiped.
Here's a quick kludge of an earlier submission (by tekangel) that avoids this by default.
Make sure it does what you want before you uncomment the unlink and rmdir commands!
<?
function rmdirRecursive($path,$followLinks=false) {

$dir = opendir($path) ;
while ( $entry = readdir($dir) ) {

if ( is_file( "$path/$entry" ) || ((!$followLinks) && is_link("$path/$entry")) ) {
echo ( "unlink $path/$entry;\n" );
// Uncomment when happy!
//unlink( "$path/$entry" );
} elseif ( is_dir( "$path/$entry" ) && $entry!='.' && $entry!='..' ) {
rmdirRecursive( "$path/$entry" ) ;
}
}
closedir($dir) ;
echo "rmdir $path;\n";
// Uncomment when happy!
// return rmdir($path);
}
?>


fkjaekel

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


brianleeholub

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


lior

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


phpcoder

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


eli dot hen

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


05-jan-2007 01: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..


contacts from nexus-soft dot org

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.


m dot winkel

The example in the previous note will stop and return false, if there is an empty subdirectory. I suggest to modify this snipplet of the previous example:
<?
$matching = glob($fileglob);
    if ($matching === false) {
         trigger_error(sprintf('No files match supplied glob %s', $fileglob), E_USER_WARNING);
         return false;
    }
?>
Here is my version:
<?
$matching = glob($fileglob);
     if ($matching === false) {
         return true;
     }
?>
If there are no matching files in the directory, there is no need to delete something or to trigger an error. It just returns true and the (empty) directory will be deleted by the rmdir command.


almann

some systems coudn´d erase directorys while they are open. So it´s better to set @closedir($dh); before trying to erase with @rmdir($dir);

not

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.


nuk

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

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...
=)


cheetah designs

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


php

In the previous examples of recursive rmdir, people should take care to use the proper way of calling readdir:
<?
while (false !== ($file = readdir($dir))) {
  // do some stuff with $file
}
?>
If you don't use this syntax, the loop will halt if it ever comes across a file named '0'.
http://www.php.net/readdir - provides more info on why this is the case.
hth
vittal


lodemessemaker

In reaction to the function rmdirr() by makarenkoa at ukrpost dot net:
If verbose is set to TRUE, it will only work in the first (target) directory, and not in subdirectories. To make the function verbose in subdirectories as well, change the following:
<?php
...
      if(is_dir($object))
          rmdirr($object);
...
?>
TO
<?php
...
      if(is_dir($object))
          rmdirr($object,$verbose);
?>


babca plutanium.cz

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


daniellehr -at- gmx -dot- de

If you want to delete a folder with its all content and sub-content you can use this recursive-working function
(WARNING: after using the function the folder is completely deleted!):
<?php
function delDir($dirName) {
   if(empty($dirName)) {
       return;
   }
   if(file_exists($dirName)) {
       $dir = dir($dirName);
       while($file = $dir->read()) {
           if($file != '.' && $file != '..') {
               if(is_dir($dirName.'/'.$file)) {
                   delDir($dirName.'/'.$file);
               } else {
                   @unlink($dirName.'/'.$file) or die('File '.$dirName.'/'.$file.' couldn\'t be deleted!');
               }
           }
       }
       @rmdir($dirName.'/'.$file) or die('Folder '.$dirName.'/'.$file.' couldn\'t be deleted!');
   } else {
       echo 'Folder "<b>'.$dirName.'</b>" doesn\'t exist.';
   }
}
?>


aidan

If you want to delete a file, or an entire folder (including the contents), use the below function.
http://aidanlister.com/repos/v/function.rmdirr.php


sarangan dot thuraisingham

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 . "
";
      }
      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 "
Removed Directory: " . $path . "
";
  }
}
#To remove a dir:
removeDir('/home/fhlinux206/t/thuraisingham.net/tmp/');
?>


bobbfwed

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>
Directory cannot be deleted until all files are deleted.</font>
';
         $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>
';
     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.


bluej100@gmail

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


dexn

Here's a short function I wrote to remove a directory and all it's contents using the glob() function:
function rmdirr($dir) {
if($objs = glob($dir."/*")){
foreach($objs as $obj) {
is_dir($obj)? rmdirr($obj) : unlink($obj);
}
}
rmdir($dir);
}


jeremiah

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
?>


swizec

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


development

Here a small and useful function for removing files by deleting also subdirectories recursive.
this function takes:
$target .. a absolute target path, f.e: /var/www/html/remove_this
$exceptions .. a array of directorynames which don't have to be removed .. usually unused as you want to delete whole directory :-)
$output=true .. outputs a status message of which file or directory the script just has accessed to;
<?php
function delete_files($target, $exceptions, $output=true)
{
$sourcedir = opendir($target);
while(false !== ($filename = readdir($sourcedir)))
{
if(!in_array($filename, $exceptions))
{
if($output)
{ echo "Processing: ".$target."/".$filename."
"; }
if(is_dir($target."/".$filename))
{
// recurse subdirectory; call of function recursive
delete_files($target."/".$filename, $exceptions);
}
else if(is_file($target."/".$filename))
{
// unlink file
unlink($target."/".$filename);
}
}
}
closedir($sourcedir);
if(rmdir($target))
{ return true; }
else
{ return false; }
}
?>
here a example of function call:
<?php
$exceptions = array(".", "..");
if(delete_files("/var/www/html/this_dir", $exceptions, true))
{ echo "deletion successed"; }
else
{ echo "deletion failed"; }
?>
KNOWN ISSUE:
if you call the function with an exception folder and that folder is a childfolder, this function won't be able to remove the parent directory and returns false .. :-/ .. if someone knows a workaround please email me :-)


webmaster

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


les_diadoques

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
\n";
       }
     }
   }
   closedir($handle);
   rmdir($dir);
   echo "removing $dir
\n";
 }
}
remove_directory("/path/to/dir");
?>


anonymous

FolderDelete ( $value );
should be
RecursiveFolderDelete ( $value );
then it's ok


brousky - gmail

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


bhuvidya

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


stefano

becouse all the examples fails if there are hiddenfiles (.filename) somewhere, I write this short and power function to erase a tree independtly from his content
/**
* rm() -- Very Vigorously erase files and directories. Also hidden files !!!!
*
* @param $dir string
*                   be carefull to:
* if($obj=='.' || $obj=='..') continue;
* if not it will erase all the server...it happened to me ;)
* the function is permission dependent.
*/
function rm($dir) {
if(!$dh = @opendir($dir)) return;
while (($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
if (!@unlink($dir.'/'.$obj)) rm($dir.'/'.$obj);
   }
  @rmdir($dir);
}


czambran

A quick note on the function posted by Daniellehr[-at-]gmx[-dot-]de, the function as it is will delete everything inside the directory but the directory. The problem is that the function does not close the directory before executing the rmdir line. Here is the corrected function:
function delDir($dirName) {
  if(empty($dirName)) {
      return true;
  }
  if(file_exists($dirName)) {
      $dir = dir($dirName);
      while($file = $dir->read()) {
          if($file != '.' && $file != '..') {
              if(is_dir($dirName.'/'.$file)) {
                  delDir($dirName.'/'.$file);
              } else {
                  @unlink($dirName.'/'.$file) or die('File '.$dirName.'/'.$file.' couldn\'t be deleted!');
              }
          }
      }
      $dir->close();
      @rmdir($dirName) or die('Folder '.$dirName.' couldn\'t be deleted!');
  } else {
      return false;
  }
  return true;
}


andreas kalsch akidee.de

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))
            {
                if (!unlink($dir.$obj))
                    return false;
               }
           }
    }
       closedir($handle);
       if (!@rmdir($dir))
        return false;
       return true;
   }
   return false;
}


formatthis

@ 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 . "
";
}
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 "
Removed Directory: " . $path . "
";
}
}
?>


mn dot yarar

/***********************************
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 doesn’t exist
}
}
function RemoveDirectory($path){
if(ClearDirectory($path)){
if(rmdir($path)){
return true;
// directory removed
}else{
return false;
// directory couldn’t 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';
}
***************************************/


makarenkoa

<?php
// rmdirr.inc.php
/*
25.07.2005
Author: Anton Makarenko
makarenkoa at ukrpost dot net
webmaster at eufimb dot edu dot ua
Original idea:
http://ua2.php.net/manual/en/function.rmdir.php
28-Apr-2005 07:35
development at lab-9 dot com
*/
function rmdirr($target,$verbose=false)
// removes a directory and everything within it
{
$exceptions=array('.','..');
if (!$sourcedir=@opendir($target))
{
if ($verbose)
echo '<strong>Couldn&#146;t open '.$target."</strong><br />\n";
return false;
}
while(false!==($sibling=readdir($sourcedir)))
{
if(!in_array($sibling,$exceptions))
{
$object=str_replace('//','/',$target.'/'.$sibling);
if($verbose)
echo 'Processing: <strong>'.$object."</strong><br />\n";
if(is_dir($object))
rmdirr($object);
if(is_file($object))
{
$result=@unlink($object);
if ($verbose&&$result)
echo "File has been removed<br />\n";
if ($verbose&&(!$result))
echo "<strong>Couldn&#146;t remove file</strong>";
}
}
}
closedir($sourcedir);
if($result=@rmdir($target))
{
if ($verbose)
echo "Target directory has been removed<br />\n";
return true;
}
if ($verbose)
echo "<strong>Couldn&#146;t remove target directory</strong>";
return false;
}
/*
// sample usage
<?php
require('./lib/rmdirr.inc.php');
rmdirr('D:/srv/Apache2/htdocs/testRm',true);
?>
//*/
?>


bishop

<?php
/**
* rm() -- Vigorously erase files and directories.
*
* @param $fileglob mixed If string, must be a file name (foo.txt), glob pattern (*.txt), or directory name.
*                        If array, must be an array of file names, glob patterns, or directories.
*/
function rm($fileglob)
{
   if (is_string($fileglob)) {
       if (is_file($fileglob)) {
           return unlink($fileglob);
       } else if (is_dir($fileglob)) {
           $ok = rm("$fileglob/*");
           if (! $ok) {
               return false;
           }
           return rmdir($fileglob);
       } else {
           $matching = glob($fileglob);
           if ($matching === false) {
               trigger_error(sprintf('No files match supplied glob %s', $fileglob), E_USER_WARNING);
               return false;
           }      
           $rcs = array_map('rm', $matching);
           if (in_array(false, $rcs)) {
               return false;
           }
       }      
   } else if (is_array($fileglob)) {
       $rcs = array_map('rm', $fileglob);
       if (in_array(false, $rcs)) {
           return false;
       }
   } else {
       trigger_error('Param #1 must be filename or glob pattern, or array of filenames or glob patterns', E_USER_ERROR);
       return false;
   }
   return true;
}
?>


andy

# Clears temporary directory and any files or sub directories
# using a stack, without evil recursion.
#
# Andy Gale - 17/11/2005
function clear_tmp_dir($dir)
{
   $stack = array($dir);
   while (count($stack)) {
       # Get last directory on stack
       $dir = end($stack);
       
       $dh = opendir($dir);
       if (!$dh) {
           trigger_error('clear_tmp_dir: unable to opendir ' . $dir, E_USER_ERROR);
       }
       
       while (($file = readdir($dh)) !== false) {
           if ($file == '.' or $file == '..') {
               continue;
           }
           if (is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
               $stack[] = $dir . DIRECTORY_SEPARATOR . $file;
           } else if (is_file($dir . DIRECTORY_SEPARATOR . $file)) {
               unlink($dir . DIRECTORY_SEPARATOR . $file);
           } else {
               trigger_error('clear_tmp_dir: ignoring ' . $dir .
                             DIRECTORY_SEPARATOR . $file, E_USER_ERROR);
           }
       }
       if (end($stack) == $dir) {
           rmdir($dir);
           array_pop($stack);
       }
   }
}


Change Language


Follow Navioo On Twitter
basename
chgrp
chmod
chown
clearstatcache
copy
delete
dirname
disk_free_space
disk_total_space
diskfreespace
fclose
feof
fflush
fgetc
fgetcsv
fgets
fgetss
file_exists
file_get_contents
file_put_contents
file
fileatime
filectime
filegroup
fileinode
filemtime
fileowner
fileperms
filesize
filetype
flock
fnmatch
fopen
fpassthru
fputcsv
fputs
fread
fscanf
fseek
fstat
ftell
ftruncate
fwrite
glob
is_dir
is_executable
is_file
is_link
is_readable
is_uploaded_file
is_writable
is_writeable
lchgrp
lchown
link
linkinfo
lstat
mkdir
move_uploaded_file
parse_ini_file
pathinfo
pclose
popen
readfile
readlink
realpath
rename
rewind
rmdir
set_file_buffer
stat
symlink
tempnam
tmpfile
touch
umask
unlink
eXTReMe Tracker