A Recursive Remove Directory Function for PHP

Remove Directory recursively

When you use classes you must call the method as $this->methodName().

Below is snipped which worked for me.

You can try this. If it gives permission error then you can add chmod function.

Remember you can not traverse a directory if you don't have read permission. So set the permission first.

   function deleteDirectory($dir) {
if (!file_exists($dir)) return true;
if (!is_dir($dir)) return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
if (!$this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
}
return rmdir($dir);
}

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

The user-contributed section in the manual page of rmdir contains a decent implementation:

 function rrmdir($dir) { 
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir. DIRECTORY_SEPARATOR .$object) && !is_link($dir."/".$object))
rrmdir($dir. DIRECTORY_SEPARATOR .$object);
else
unlink($dir. DIRECTORY_SEPARATOR .$object);
}
}
rmdir($dir);
}
}

Delete directory with files in it?

There are at least two options available nowadays.

  1. Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example:

    public static function deleteDir($dirPath) {
    if (! is_dir($dirPath)) {
    throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
    $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
    if (is_dir($file)) {
    self::deleteDir($file);
    } else {
    unlink($file);
    }
    }
    rmdir($dirPath);
    }
  2. And if you are using 5.2+ you can use a RecursiveIterator to do it without implementing the recursion yourself:

    $dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree';
    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it,
    RecursiveIteratorIterator::CHILD_FIRST);
    foreach($files as $file) {
    if ($file->isDir()){
    rmdir($file->getRealPath());
    } else {
    unlink($file->getRealPath());
    }
    }
    rmdir($dir);

In PHP how do I recursively remove all folders that aren't empty?

From the first comment in the official documentation.

http://php.net/manual/en/function.rmdir.php

<?php

// When the directory is not empty:
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);
}
}

?>

Edited rmdir to rrmdir to correct typo from obvious intent to create recursive function.

Remove all files, folders and their subfolders with php

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

Try out the above code from php.net

Worked fine for me

How do I remove a directory that is not empty?

There is no built-in function to do this, but see the comments at the bottom of http://us3.php.net/rmdir. A number of commenters posted their own recursive directory deletion functions. You can take your pick from those.

Here's one that looks decent:

function deleteDirectory($dir) {
if (!file_exists($dir)) {
return true;
}

if (!is_dir($dir)) {
return unlink($dir);
}

foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}

if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}

}

return rmdir($dir);
}

You could just invoke rm -rf if you want to keep things simple. That does make your script UNIX-only, so beware of that. If you go that route I would try something like:

function deleteDirectory($dir) {
system('rm -rf -- ' . escapeshellarg($dir), $retval);
return $retval == 0; // UNIX commands return zero on success
}

PHP recursively delete empty parent directories

Because this has some overhead, I'm going to suggest that you only do this from PHP if absolutely needed. You can use the Linux find command for this:

find /path/to/dir -empty -type d -delete

I would put that in a cron job. If you like you can use the php system command to do this though:

system('find /path/to/dir -empty -type d -delete', $retval);

Using this you would simply delete the file and then let this run only every day or so to go through and take care of any empty directories. This may seem more hackish than making it all in PHP but it'll run much faster. It is less portable but that shouldn't matter too much for most sites. Save this as rdel.bat (I walways make sure you have the [Show hidden file extensions][2] explorer folder option turned on but if you don't then use the drop-down in your text editors Save As... dialog to ensure it has the proper extension).

UPDATE:

To do the same thing in Windows use a batch file with just this one line:

for /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d"

Test this by changing to a directory and running your new file. It should remove any empty directories below the current.

To schedule this just add an entry to your task scheduler. That is a little different depending on which version of Windows you use. Be sure to set the working directory correctly (this is how the batch file knows where to start).

The problem with this is that in Windows a lot of junk files get created in empty directories (ie Thumbs.db). You can handle that by adding code to your batch file to remove any of those files too:

del /s /q Thumbs.db

Add this above the other line and repeat for anything else which may be unneeded.

PHP recursive delete function

Try something like this:

$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('%yourBaseDir%'),
RecursiveIteratorIterator::CHILD_FIRST
);

$excludeDirsNames = array();
$excludeFileNames = array('.htaccess');

foreach($it as $entry) {
if ($entry->isDir()) {
if (!in_array($entry->getBasename(), $excludeDirsNames)) {
try {
rmdir($entry->getPathname());
}
catch (Exception $ex) {
// dir not empty
}
}
}
elseif (!in_array($entry->getFileName(), $excludeFileNames)) {
unlink($entry->getPathname());
}
}


Related Topics



Leave a reply



Submit