Recursively deleting a folder in PHP

Submitted by:Jhon Jhon

Date added:04 June, 2015

Category:PHP

PHP’s rmdir function does not allow the deletion of a folder if it is not empty.

Tags: php delete , delete a folder

Code Snippet:

/** -rf on linux.
* Delete a file, or a folder and its contents (recursive algorithm)
*
* @author Aidan Lister <aidan@php.net>
* @version 1.0.3
* @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);
}

// Loop through the folder
$dir = dir($dirname);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}

// Recurse
rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
}

// Clean up
$dir->close();
return rmdir($dirname);
}


/**All good code should include tests, so here we go: */

// Create a directory and file tree
mkdir('testdelete');
mkdir('testdelete/one-a');
touch('testdelete/one-a/testfile');
mkdir('testdelete/one-b');

// Add some hidden files for good measure
touch('testdelete/one-b/.hiddenfile');
mkdir('testdelete/one-c');
touch('testdelete/one-c/.hiddenfile');

// Add some more depth
mkdir('testdelete/one-c/two-a');
touch('testdelete/one-c/two-a/testfile');
mkdir('testdelete/one-d/');

// Test that symlinks are not followed
mkdir('testlink');
touch('testlink/testfile');
symlink(getcwd() . '/testlink/testfile', 'testdelete/one-d/my-symlink');
symlink(getcwd() . '/testlink', 'testdelete/one-d/my-symlink-dir');

// Run the actual delete
$status = rmdirr('testdelete');

// Check if we passed the test
if ($status === true &&
!file_exists('testdelete') &&
file_exists('testlink/testfile')) {
echo 'TEST PASSED';
rmdirr('testlink');
} else {
echo 'TEST FAILED';
}
 
 

Comments