Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple script to recursively delete all files and directories within a parent directory
<?php
/**
* @param string $directory
*/
function emptyDirectoryContents($directory)
{
$Iterator = new RecursiveIteratorIterator(
new \RecursiveDirectoryIterator(
realpath($directory),
FilesystemIterator::SKIP_DOTS
), RecursiveIteratorIterator::CHILD_FIRST
);
/** @var \SplFileInfo $file */
foreach ($Iterator as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
}
@settermjd

This comment has been minimized.

Copy link
Owner Author

settermjd commented Feb 24, 2016

Need to wrap the RecursiveIteratorIterator in a RegexIterator or something similar. That way I can be sure I'm only deleting the files and directories which are required, not anything and everything, such as .gitkeep files etc.

@SenseException

This comment has been minimized.

Copy link

SenseException commented Feb 24, 2016

rmdir deletes only empty directories.

@settermjd

This comment has been minimized.

Copy link
Owner Author

settermjd commented Feb 25, 2016

thanks @SenseException. It's an evolving work in progress. Should be finished a first version by the end of tomorrow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.