Non-Recursively Deleting A Folder In PHP

In PHP, you can’t just delete a folder using rmdir unless the folder’s empty. You can, however, do so using rmdirr function, wherein it will remove both the folder and its contents recursively. But using this [recursive] method opens up the possibility for PHP to segfault/crash, specifically and especially if you have deeply nested directories of a thousand or so.

Here’s a nice alternative method by Aidan Lister on deleting folders without using the recursive method, which is the stack-based (as opposed to the recursion based) version of rmdirr.

/**
 * Delete a file, or a folder and its contents (stack algorithm)
 *
 * @author      Aidan Lister <[email protected]>
 * @version     1.0.0
 * @link        http://aidanlister.com/repos/v/function.rmdirr.php
 * @param       string   $dirname    Directory to delete
 * @return      bool     Returns TRUE on success, FALSE on failure
 */
function rmdirr($dirname)
{
 // Sanity check
 if (!file_exists($dirname)) {
 return false;
 }
 // Simple delete for a file
 if (is_file($dirname) || is_link($dirname)) {
 return unlink($dirname);
 }
 // Create and iterate stack
 $stack = array($dirname);
 while ($entry = array_pop($stack)) {
 // Watch for symlinks
 if (is_link($entry)) {
 unlink($entry);
 continue;
 }
 // Attempt to remove the directory
 if (@rmdir($entry)) {
 continue;
 }
 // Otherwise add it to the stack
 $stack[] = $entry;
 $dh = opendir($entry);
 while (false !== $child = readdir($dh)) {
 // Ignore pointers
 if ($child === '.' || $child === '..') {
 continue;
 }
 // Unlink files and add directories to stack
 $child = $entry . DIRECTORY_SEPARATOR . $child;
 if (is_dir($child) && !is_link($child)) {
 $stack[] = $child;
 } else {
 unlink($child);
 }
 }
 closedir($dh);
 print_r($stack);
 }
 return true;
}     

Incoming search terms for the article:

Related Posts

eBag Toolkit

Creating a Psychedelic Art Effect in Your Portraits

Inspirational Photo Retouches By Cristian Girotto

Create Your Own Sticker Design Via Photoshop