Skip to content

Instantly share code, notes, and snippets.

@settermjd
Created February 24, 2016 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save settermjd/66e571c76714c5364891 to your computer and use it in GitHub Desktop.
Save settermjd/66e571c76714c5364891 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link

rmdir deletes only empty directories.

@settermjd
Copy link
Author

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